比如下面的代码:
struct pnames {
char * first;
char * last;
};
struct pnames tt;
scanf("Please enter the first name: %s", tt.first);
scanf("Please enter the last name: %s", tt.last);
由于定义了struct pnames类型的变量tt,但是并没有初始化该变量。所以first,last的值有可能会指向内存中的任何区域。后边如果scanf对first,last指向的内存区域做修改,可能导致意想不到的问题。而使用char数组则没有问题,比如:
struct pnames {
char first[20];
char last[20];
};
struct pnames tt;
scanf("Please enter the first name: %s", tt.first);
scanf("Please enter the last name: %s", tt.last);
此时定义了变量tt,就会为first,last分配固定的空间,用来保存用户通过scanf的输入。这样保证了安全性。
有一种情况我们可以使用在struct中使用字符指针,就是我们可以结合malloc(),来根据用户输入的字符长度申请相应的同等大小内存来保存。比如:
struct pnames {
char * first;
char * last;
};
struct pnames tt;
char first[20];
char last[20];
scanf("Please enter the first name: %s", first);
scanf("Please enter the last name: %s", last);
tt.first = (char *) malloc(strlen(first)+1);
tt.last = (char *) malloc(strlen(last)+1);
但是这样做,一定要用free去释放内存,否则程序退出时会导致内存泄漏。