【发布时间】:2013-06-14 15:20:56
【问题描述】:
我的程序出了什么问题,当我尝试打印值时出现段错误。
我的目标是在 sample_function 中分配一些值。
在主函数中,我想将结构复制到另一个结构。
#include<stdio.h>
#include<string.h>
typedef struct
{
char *name;
char *class;
char *rollno;
} test;
test *
sample_function ()
{
test *abc;
abc = (test *)malloc(sizeof(test));
strcpy(abc->name,"Microsoft");
abc->class = "MD5";
abc->rollno = "12345";
printf("%s %s %s\n",abc->name,abc->class,abc->rollno);
return abc;
}
int main(){
test *digest_abc = NULL;
test *abc = NULL;
abc = sample_function();
digest_abc = abc;
printf(" %s %s %s \n",digest_abc->name,digest_abc->class,digest_abc->rollno);
return 1;
}
指针一直是我的噩梦,我一直不明白。
【问题讨论】:
-
你没有为
abc分配内存 => 未定义的行为。 -
您不需要在 C 程序中强制转换
malloc的返回值。 -
为什么你只使用 strcpy 作为 name 而不是 class 和 rollno?