我遇到了这个程序的问题。 这很简单。 我需要从我创建的指针中为我的结构赋值,但是我一直遇到分段错误。 我有什么想法我做错了:
#include #include struct problem37 { int a; int b; int c; }; int main() { printf("Problem 37n"); //create struct struct problem37 myStruct; //create the pointer int* p; int* q; int* r; *p = 1; *q = 5; *r = 8; //read the data into the struct using the pointers myStruct.a = *p; myStruct.b = *q; myStruct.c = *r; printf("%dn", myStruct.a); printf("%dn", myStruct.b); printf("%dn", myStruct.c); return 0; }
您正在为*p
, *q
和*r
分配值,但它们未初始化:它们是指向随机存储器的指针。
您需要初始化它们,或者为它们分配在堆中分配的新值(使用malloc
):
int *p = (int*) malloc( sizeof(int) ); *p = 1;
或使它们指向已存在的值:
int x; int *p = &x; *p = 1; // it's like doing x=1
您的问题是您在随机内存位置写入,因为您没有初始化指针也没有分配内存。
您可以执行以下操作:
int* p = malloc(sizeof(int)); int* q = malloc(sizeof(int)); int* r = malloc(sizeof(int));
显然你需要在使用它们时释放它们:
free(p); free(q); free(r);
你没有为指针分配内存。 因此,当您执行* p和* q和* r时,您将取消引用空指针(或随机指针)。 这导致分段错误。 使用p = malloc(sizeof(int)); 当你声明变量时。
需要了解更多c/c++开发分享C结构指针 – 分段故障,也可以关注C/ C++技术分享栏目—计算机技术网(www.ctvol.com)!
以上就是c/c++开发分享C结构指针 – 分段故障相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/978841.html