Welcome

首页 / 软件开发 / C语言 / C结构中使用字符指针

C结构中使用字符指针2010-09-23zhangjunhd下面的例子定义了两个结构,由于成员中存在字符串,所以结构一使用了字符数组,而结构二使用字符指针。

#include <stdio.h>
#define LEN 20
struct info {
char first[LEN];
char last[LEN];
int age;
};
struct pinfo {
char * first;
char * last;
int age;
};
int main()
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old. ", one.first, one.last, one.age);
printf("%s %s is %d years old. ", two.first, two.last, two.age);
return 0;
}

代码运行正常。但是对于struct pinfo变量 two来说,存在隐患。因为two中的两个字符串存储在文字常量区。而在结构中存放的只是两个地址而已。

printf("one.first"s size: %d ",sizeof(one.first));
printf("two.first"s size: %d ",sizeof(two.first));

结果:

one.first"s size: 20
two.first"s size: 4