码迷,mamicode.com
首页 > 编程语言 > 详细

C语言:十九 程序找错 结构体内的指针使用前要确定指向

时间:2020-01-29 10:40:12      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:strcpy   错误   情况下   null   sizeof   student   eof   str   ret   

程序一:
struct student
{
char *name;
int score;
} stu,*pstu;

int main()
{
strcpy(stu.name,"Jimy");
stu.score = 99;
return 0;
}
问程序有何错误?

答:错误在于struct中只是定义了指针name,并未分配空间的情况下就strcpy。
应在main中strcpy之前加上:
stu.name=(char*)malloc(sizeof(char)*某数)

程序二:
int main()
{
pstu = (struct student *)malloc(sizeof(struct student));
strcpy(pstu->name,"Jimy");
pstu->score=99;
free(pstu); //记得释放指针,最好加一句pstu= NULL
return 0;
}
解析:
尽管分配了结构体指针pstu指向的内存空间,但成员name指针扔未被分配空间,应在strcpy前加上:
pstu->name = (char*)malloc(sizeof(char)*某数)

C语言:十九 程序找错 结构体内的指针使用前要确定指向

标签:strcpy   错误   情况下   null   sizeof   student   eof   str   ret   

原文地址:https://www.cnblogs.com/wuqi1003/p/12239665.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!