In the case of the structure with a pointer
#include<stdio.h> struct man { char *name; int age; }; int main() { struct man m = {"tom",20}; printf("name = %s, age = %d\n",m.name,m.age); return 0; }
operation result:
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot @ ubuntu: ~ / wangqinghe / C / 20190714 $ ./struct
name = tom, age = 20
If you modify the value of m.name
#include<stdio.h> #include<string.h> struct man { char *name; int age; }; int main() { struct man m = {"tom",20}; strcpy(m.name,"mike"); printf("name = %s, age = %d\n",m.name,m.age); return 0; }
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot @ ubuntu: ~ / wangqinghe / C / 20190714 $ ./struct
Segmentation fault (core dumped)
The above error.
Change the pointer bit array:
#include<stdio.h> #include<string.h> struct man { char name[256]; int age; }; int main() { struct man m = {"tom",20}; strcpy(m.name,"mike"); printf("name = %s, age = %d\n",m.name,m.age); return 0; }
Compile and run:
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot @ ubuntu: ~ / wangqinghe / C / 20190714 $ ./struct
name = mike, age = 20
analysis:
Numerical constants in memory can not be modified.
#include<stdio.h> #include<string.h> #include<stdlib.h> struct man { char *name; int age; }; int main() { //struct man m = {"tom",20}; struct man m; m.name = malloc(sizeof(char) * 100); m.age = 20; strcpy(m.name,"mike"); printf("name = %s, age = %d\n",m.name,m.age); return 0; }
Compile and run:
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot @ ubuntu: ~ / wangqinghe / C / 20190714 $ ./struct
name = mike, age = 20
#include<stdio.h> #include<string.h> #include<stdlib.h> struct man { char *name; int age; }; int main() { struct man *p = malloc(sizeof(struct man)); p->name = malloc(sizeof(char) * 100); strcpy(p->name,"tom"); p->age = 30; printf("name = %s, age = %d\n",p->name,p->age); free(p->name); free(p); return 0; }
Pointer memory storage:
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot @ ubuntu: ~ / wangqinghe / C / 20190714 $ ./struct
name = tom, age = 30
END