我的代码有问题,我无法在结构中将字符串值分配给char *。有人可以告诉我我的代码有什么问题吗?为什么?

#include <iostream>
using namespace std;

typedef struct{
char* name;
char* city;
int age;
} person;
void main()
{
person * user;
user = (person*)malloc(sizeof(person*));

cout << "Please fill in the user info.." << endl << "Name: ";
cin >> user->name;
cout << "Age: ";
cin >> user->age;
cout << "City";
cin >> user->city;

cout << "The user info is:" << endl << "Name: " << user->name << endl << "Age: " << user->age << endl << "City: " << user->city << endl;
system("pause");
}


非常感谢你。

最佳答案

正如Mike的评论所说,您的代码是C和C ++风格的可怕结合,选择一种语言并正确使用它。

#include <iostream>
#include <string>
using namespace std;

struct person {
  string name;
  string city;
  int age;
};

int main()
{
  person user;

  cout << "Please fill in the user info.." << endl << "Name: ";
  cin >> user.name;
  cout << "Age: ";
  cin >> user.age;
  cout << "City";
  cin >> user.city;

  cout << "The user info is:\n" << "Name: " << user.name << "\nAge: " << user.age << "\nCity: " << user.city << endl;
  system("pause");
}


不需要时不要动态分配(这样就不会存在分配错误的内存量的风险,也不会为字符串分配内存的风险,这都是您在原始程序中犯的错误)。

main必须返回int而不是void

在C ++中不需要typedef struct {...} x;,只需说struct x {...};

Don't overuse endl

10-06 10:38