【发布时间】:2014-12-09 12:19:20
【问题描述】:
我的代码有问题,我无法将字符串值分配给结构中的 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");
}
非常感谢。
【问题讨论】:
-
选择一种语言。如果是 C,不要使用
cin,并为字符串分配一些内存。如果是 C++,请使用std::string,不要使用malloc或原始指针。如果它是两者的可怕混合,那么现在就放弃吧。 -
请澄清“无法分配字符串值”的含义。该代码中只有一个赋值,即
user = ...。 (并且不要在 C++ 中使用malloc,使用new。) -
尝试更改“user = (person*)malloc(sizeof(person*));” to "user = (person*)malloc(sizeof(person)); "
-
@molbdnilo 不要使用
new。 -
抱歉,这段代码有很多问题。当错误层层出现时,很难解释什么是错误的。是的,这很残酷,但有时现实很残酷。 C 和 C++ 与典型的脚本语言有很大不同,并且需要您对内存处理有扎实的掌握。在您了解指针和内存管理之前,请获得一个好的 C 教程,并且永远不要接触 C++。当您准备好使用 C++ 时,您应该了解如何以及为什么将
malloc替换为new/delete,然后在您了解了new/delete的替代方案之后,您可以在实际项目中使用 c++ .