C语言 用string型数据遇到的问题

来源:百度知道 编辑:UC知道 时间:2024/06/25 20:06:17
例如下面的小测试程序,使用了string型数据,会弹框,换用字符数组则正常.请问这是为什么?

#include <iostream>
using namespace std;
#include<string>
struct student
{
int sID;
string name;
int age;
student(int ,string,int);
student();
};
student::student(){}
student::student(int id,string n,int a)
{
sID=id;
name=n;
age=a;
}
//定义学生表结构体///////////////
struct SList
{
student *stu;
int length;
int listsize;
};
int main()
{
SList l;
student e;
e.name="maple";
e.sID=1;
e.age=20;
l.stu=(student *)malloc(50*sizeof(student));
l.stu[0]=e;
return 0;
}

如果真的想使用string,建议你将student的指针存放在链表中,可以参考下面代码:
#include <iostream>
using namespace std;
#include<string>
struct student
{
int sID;
string name;
int age;
student(int ,string,int);
student();
};
student::student(){}
student::student(int id,string n,int a)
{
sID=id;
name=n;
age=a;
}
//定义学生表结构体///////////////
struct SList
{
student **stu;
int length;
int listsize;
};
int main()
{
SList l;
student *e = new student(1, "maple", 20);
// e.name="maple";
// e.sID=1;
// e.age=20;
l.stu=new student *[1];
l.stu[0]=e;
// 因为动态分配的内存,程序退出时一定要释放,不然会造成内存泄露
delete l.stu[0];
delete [] l.stu;
return 0;
}

student *stu;
是一个指针不是指针数组!更不是指向指针的指针
#include <iostream>
#include<string>
using namespace std;
struct student
{