27 lines
940 B
C
27 lines
940 B
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
char *names[5]; // names 数组用来存储地址,每个元素都是 char *, 等同于 5 个字符串
|
||
|
for (int i = 0; i < 5; i++)
|
||
|
{
|
||
|
printf("请输入第 %d 个姓名: ", i + 1);
|
||
|
names[i] = (char *)malloc(32); // 为什么需要申请内存?因为 names[i] 是 char * 类型,需要存储字符串,所以需要申请内存,否则会出现段错误,因为 names[i] 指向的内存是不可写的 // names + i => &names[i]
|
||
|
scanf("%s", names[i]); // names + i => &names[i]
|
||
|
}
|
||
|
for (int i = 0; i < 5; i++)
|
||
|
{
|
||
|
printf("%s\n", *(names + i));
|
||
|
}
|
||
|
printf("%p\n", names[0]);
|
||
|
printf("%s\n", names[0]);
|
||
|
for (int i = 0; i < 5; i++)
|
||
|
{
|
||
|
free(names[i]);
|
||
|
}
|
||
|
printf("%p\n", names[0]);
|
||
|
printf("%s\n", names[0]); // 内存释放后,地址不变,但是地址中的内容清空了
|
||
|
|
||
|
return 0;
|
||
|
}
|