C结构指针 – 分段故障

我遇到了这个程序的问题。 这很简单。 我需要从我创建的指针中为我的结构赋值,但是我一直遇到分段错误。 我有什么想法我做错了:

#include  #include  struct problem37 { int a; int b; int c; }; int main() { printf("Problem 37\n"); //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("%d\n", myStruct.a); printf("%d\n", myStruct.b); printf("%d\n", 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)); 当你声明变量时。