struct stu {
string name;//用string定义name
int a;
};
int main() {
stu s;
struct stu* ps = (stu*)malloc(5 * sizeof(stu));//malloc动态开辟内存
if (ps == NULL) {
perror("");
return 0;
}
cin >> ps->name;//写入,程序在这里崩溃
cout << ps->name;
free(ps);
ps = NULL;
return 0;
}
但是如果把string name 换成char name[20]就可以运行,为什么啊?
struct stu {
char name[20];//换成字符数组定义
int a;
};
int main() {
stu s;
struct stu* ps = (stu*)malloc(5 * sizeof(stu));
if (ps == NULL) {
perror("");
return 0;
}
cin >> ps->name;
cout << ps->name;
free(ps);
ps = NULL;
return 0;
}