注册 登录
编程论坛 C++教室

结构体中含有char*类型

九天冥盟 发布于 2017-11-16 21:37, 1888 次点击
问题是:c++中,当结构体中含有char* 类型时,为什么在运行时输入 一串字符串 之后就不能继续运行了;

简单代码如下:
#include <iostream>
using namespace std;
struct Student
{
    char *name;
    int age;
    int height;
};

void massage_i(Student &a)
{
    cout<<"name:";
    cin>>a.name;
    cout<<"age:";
    cin>>a.age;
    cout<<"height:";
    cin>>a.height;
}

void display(Student temp)
{
    cout<<temp.name<<"\t"<<temp.age<<"\t"<<temp.height;
}

int main()
{
    Student stu;
    massage_i(stu);
    display(stu);
    return 0;
}
调试了一下,发现stu.name区域显示0x1d error:cannot access memory at address
请问是什么地方错了吗?如果坚持要用 char *类型输入那该怎么修改?????

   
4 回复
#2
rjsp2017-11-16 22:01
cin>>a.name; 是输入一串字符到a.name指向的内存中,但你的a.name指向哪里?
#3
九天冥盟2017-11-18 16:42
回复 2楼 rjsp
你的意思是  我没有声明内存?
#4
九天冥盟2017-11-18 17:08
#include <iostream>
using namespace std;
#include "string.h"
#include "stdlib.h"
struct Student
{
    char *name;
    int age;
    int height;
};

void massage_i(Student &a)
{
    char *name_p;
    cout<<"name:";
    cin>>name_p;
    cout<<"age:";
    cin>>a.age;
    cout<<"height:";
    cin>>a.height;
    if(strdup(name_p)==NULL)
       cout<<"error";
    else
      a.name=strdup(name_p);

}

void display(Student temp)
{
    cout<<temp.name<<"\t"<<temp.age<<"\t"<<temp.height;
     free(temp.name);
}

int main()
{
    Student stu;
    massage_i(stu);
    display(stu);
    return 0;
}

怎么还是这样?
#5
rjsp2017-11-18 19:59
Student stu;
   stu.name = new char[足够的长度]:
massage_i(stu);
1