C++ 大大增强了对字符串的支持,除了可以使用C风格的字符串,还可以使用内置的 string 类。string 类处理起字符串来会方便很多,完全可以代替C语言中的字符数组或字符串指针。
但是想要在链表中存储string类型的数据不能用在普通链表中的申请内存方法。(调试了半天,用了头插法、尾插法等等好几种方法,终于在逐条调试语句中发现每次都是在输入数据赋值给结构体中的string类型变量时报错!!!好再找到了错误,又学到了新的知识!!!)
node* p=(node*)malloc(sizeof(node))
例如在下面代码中我想要把结构体数据存入到链表中,用malloc进行申请内存,在输入第一个数据时就会引发异常。
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
typedef struct node
{
string name;
string gender;
int phonenumber;
struct node* next;
}node, * linklist;
void creatlist(linklist& L, int x)
{
linklist r;
L = (linklist)malloc(sizeof(node));
L->next = NULL;
r = L;
for (int i = 0; i < x; i++)
{
node* p = (linklist)malloc(sizeof(node));
cin >> p->name >> p->gender >> p->phonenumber;
r->next = p;
r = p;
}
r->next = NULL;
}
void list_show(linklist L)
{
if (!L->next) return;
node* p = L->next;
while (p)
{
cout << "姓名:" << p->name << " 性别:" << p->gender << " 联系方式:" << p->phonenumber << endl;
p = p->next;
}
}
int main()
{
linklist L = 0;
int x = 3;
creatlist(L, x);
list_show(L);
return 0;
}
如图会发生访问冲突
由于string类是C++新增加的类,在使用string时会自动调用它的默认构造函数。C中的malloc() 只是申请内存,它不会调用string类的构造函数。所以我们可以使用C++中的new()来替代malloc(),new不仅仅会申请内存,而且会调用string类的构造函数。(参考博客new()的用法)
所以,我们可以把用malloc申请结点p用new来进行替换
node* p=new node();
接下来我们在原程序中进行更改
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
typedef struct node
{
string name;
string gender;
int phonenumber;
struct node* next;
}node, * linklist;
void creatlist(linklist& L, int x)
{
linklist r;
L = (linklist)malloc(sizeof(node));
L->next = NULL;
r = L;
for (int i = 0; i < x; i++)
{
node* p =new node();
cin >> p->name >> p->gender >> p->phonenumber;
r->next = p;
r = p;
}
r->next = NULL;
}
void list_show(linklist L)
{
if (!L->next) return;
node* p = L->next;
while (p)
{
cout << "姓名:" << p->name << " 性别:" << p->gender << " 联系方式:" << p->phonenumber << endl;
p = p->next;
}
}
int main()
{
linklist L = 0;
int x = 3;
creatlist(L, x);
list_show(L);
return 0;
}
输入数据可以发现程序运行正常。