为结构中的 char* 赋值 [英] Assigning a value to char* in a struct

查看:76
本文介绍了为结构中的 char* 赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problem with my code i cant assign a string value into char* in a struct. Can someone tell me what is wrong with my code and why?

#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 和 C++ 风格的可怕混合,正如 Mike 的评论所说,选择一种语言并正确使用它.

Your code is a horrible mix of C and C++ style, as Mike's comment says, pick a language and use it properly.

#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");
}

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

Don't dynamically allocate when you don't need to (then there's no risk of mallocing the wrong amount of memory, and no risk of not mallocing memory for the strings, which are both mistakes you made in your original program).

main 必须返回 int 而不是 void

main must return int not void

typedef struct {...} x; 在C++中不是必须的,直接说struct x {...};

typedef struct {...} x; is not necessary in C++, just say struct x {...};

不要过度使用endl

这篇关于为结构中的 char* 赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆