Thread 1: EXC_BAD_ACCESS(当结构体遇上指针)

#include 

typedef struct B {
     
   int data1;
   int data2;
   struct B *data3;
} B;

int main() {
     
   B *c;
   c->data1 = 1;
   c->data2 = 4;
   printf("\n%d\n", c->data1);
}

Thread 1: EXC_BAD_ACCESS (code=2, address=0x100009025)


#include 
#include 

typedef struct B {
     
   int data1;
   int data2;
   struct B *data3;
} B;

int main() {
     
   B *c=(B*)malloc(sizeof(B));
   c->data1 = 1;
   c->data2 = 4;
   printf("\n%d\n", c->data1);
}

1 Program ended with exit code: 0


#include 

typedef struct B {
     
   int data1;
   int data2;
   struct B *data3;
} B, *b;

int main() {
     
   B c;
   c.data1 = 1;
   c.data2 = 4;
   printf("\n%d\n", c.data1);
}

1 Program ended with exit code: 0


总之就是用指针的时候必须先开辟动态存储空间

你可能感兴趣的:(C大讨论,结构体,指针,c语言)