比如下面的代码:
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去释放内存,否则程序退出时会导致内存泄漏。
探讨了在C语言中使用结构体存储字符串时,直接使用字符数组与使用字符指针的区别。分析了未初始化的指针可能带来的风险,以及如何通过malloc动态分配内存来解决这一问题,但同时强调了使用free释放内存的重要性以避免内存泄漏。
796

被折叠的 条评论
为什么被折叠?



