在c++中通过指针设置/获取值
Setting/getting values through pointers in C++
我正在努力学习指针在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.str
或something->str
,请将其替换为something.str.c_str()
同样,%d
期望将int
作为参数,但您传递的是double
。要打印something.y
和something.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;
相关文章:
- 如何获取进程以设置其亲和力?
- 如何获取控制面板设置值,如字体大小
- 获取和设置函数 c++
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 在 C++ 中将函数获取和设置为虚拟函数
- Qt 原子 int 获取并立即设置
- 提升获取文本的区域设置"Conversion failed"
- 如何使用C++获取/设置OBS中的垂直滚动过滤器属性?
- 在通过 P/Invoke 获取的 C++ 结构上设置 C# 回调
- 如何在Windows中获取和设置系统音量
- 如何设置获取类的私有成员:寻找更好的方法
- 在 c++ 中为我的类设置/获取方法时遇到问题
- 通过 C/C++ 使用 JPEG 像素格式在 v4l2 中设置/获取相机 JPEG 压缩质量
- C++字符串和设置/获取函数
- 如何制作一个好的设置/获取方法
- 设置获取指针
- 在c++中通过指针设置/获取值
- 设置/获取 Java 列表<>从 C 代码
- 在窗口模式下设置/获取我的绝对鼠标位置
- 使用复共轭来设置/获取数组值的代理