通过C ++中的指针设置/获取值

时间:2014-08-17 13:47:18

标签: c++ pointers

我正在尝试学习指针在C ++中是如何工作的,除了最后一小时我只是设法让它崩溃。

#include<string>

// a sample structure
typedef struct test_obj_type_s{

    // with some numbers
    int x; 
    float y;
    double z;

    std::string str; // a standard string...
    char * str2; // a variable-length string...
    char str3[2048]; // a fixed-length string...

    struct test_obj_type_s *next; // and a link to another similar structure
} test_obj_type_t;

// a sample pointer
test_obj_type_t * last_test_obj;
test_obj_type_t obj;

// let's go
int main(){

    // let's assign some demo values
    obj.x = 12;
    obj.y = 15.15;
    obj.z = 25.1;
    obj.str = "test str is working";
    obj.str2 = "test str2 is working";
    strcpy_s(obj.str3, "test str3 is working"); 

    // let's also assign some circular references
    obj.next = &obj; 

    // now...
    last_test_obj = &obj;

    test_obj_type_t * t1 = last_test_obj;
    test_obj_type_t t2 = obj;

    // now let's have some fun;
    printf("%d %d %d %s %s %s", t2.x, t2.y, t2.z, t2.str, t2.str2, t2.str3);
    printf("%d %d %d %s %s %s", t2.next->x, t2.next->y, t2.next->z, t2.next->str, t2.next->str2, t2.next->str3);
    printf("%d %d %d %s %s %s", t1->x, t1->y, t1->z, t1->str, t1->str2, t1->str3);
    printf("%d %d %d %s %s %s", t1->next->x, t1->next->y, t1->next->z, t1->next->str, t1->next->str2, t1->next->str3);

    printf("I survived!");
}

我错过了什么? 或者我做错了什么?

2 个答案:

答案 0 :(得分:4)

您的程序在将std::string传递给printf时会出现未定义的行为。 %s格式说明符需要const char*作为参数。在something.str系列something->str语句中,您printfsomething.str.c_str()的任何地方都将其替换为%d

同样,int期望double作为参数,但您要传递something.y。要打印something.z%f,请改用{{1}}说明符。

答案 1 :(得分:1)

您可以转到c ++流输出,这是执行此类操作的更简单方法:

// now let's have some fun;
std::cout<<t2.x<<t2.y<<t2.z<<t2.str<<t2.str2<<t2.str3<<std::endl;
std::cout<<t2.next->x<<t2.next->y<<t2.next->z<<t2.next->str<<t2.next->str2<<t2.next->str3<<std::endl;
std::cout<<t1->x<<t1->y<<t1->z<<t1->str<<t1->str2<<t1->str3<<std::endl;
std::cout<<t1->next->x<<t1->next->y<<t1->next->z<<t1->next->str<<t1->next->str2<<t1->next->str3<<std::endl;