结构体中带有指针的情况
#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; }
运行结果:
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot@ubuntu:~/wangqinghe/C/20190714$ ./struct
name = tom, age = 20
如果修改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
段错误 (核心已转储)
会出现以上错误。
将指针改位数组:
#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; }
编译运行:
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 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; }
编译运行:
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; }
指针在内存的存储方式:
exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct.c -o struct
exbot@ubuntu:~/wangqinghe/C/20190714$ ./struct
name = tom, age = 30
END