有问题吗?
#include <stdio.h> #include <string.h> struct Test { int x; char *str; }; int main() { struct Test a; a.x=100; char s[]="Hello"; strcpy(a.str,s); printf("%d %s\n", a.x, a.str); return 0; }
正解——当有指针数据成员,必须先为其分配空间!
#include <stdio.h> #include <string.h> #include <malloc.h> struct Test { int x; char *str; }; int main() { struct Test a; a.x=100; char s[]="Hello"; a.str=(char*)malloc(strlen(s)+1); strcpy(a.str,s); printf("%d %s\n", a.x, a.str); return 0; }
时间: 2024-12-21 18:54:38