在c++中通过指针设置/获取值

Setting/getting values through pointers in C++

本文关键字:设置 获取 指针 c++      更新时间:2023-10-16

我正在努力学习指针在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!");
}

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

程序将std::string传递给printf时显示未定义行为。%s格式指定符需要一个const char*作为参数。在您的printf语句系列中,任何地方都有something.strsomething->str,请将其替换为something.str.c_str()

同样,%d期望将int作为参数,但您传递的是double。要打印something.ysomething.z,请使用%f指定符。

您可以移动到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;