关于sting类型在结构体中的有关问题

关于sting类型在结构体中的问题
首先,请无视我将c和c++无厘头混用的问题,其实我的初衷使用c来完成一个链表,但是对于数据类型,我比较喜欢用string,我已经试过了,char*类型可以不出错的运行,但是为什么string类型就会出错,求大神解答。。。。。(cout以后会改成printf,因为我很清楚这一种混用编程风格很糟糕,请先无视这些。。。

加问一句,怎么样可以让代码在网页里想编译器中的显示方式?我试过code标签,不顶用。万分感谢,小弟刚入门,分不多,望大神们理解下,
不废话了,上代码:


如下代码
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string>
using namespace std;
typedef struct Node *PtrNode;
typedef PtrNode list;
typedef PtrNode Position;
struct Node {
string cityNname;
int locationX;
int locationY;
PtrNode Next;
};
int main(){
list l;
string temp("hello");
l = (list)malloc(sizeof(struct Node));
if(l == NULL)
printf("overflow !\n");
l->Next = NULL;
l->locationY = 1;
l->locationX = 2;
l->cityNname = temp; //这里除了问题,我逐步调试的时候说是这里出了访问冲突的问题?
cout << l->locationY << endl;
cout << l->locationX << endl;
cout << l->cityNname << endl;
return 0;
}




------解决方案--------------------
吧 malloc 换成 new

malloc只是申请内存,没有调用构造函数


------解决方案--------------------
string cityNname;是C++类型,C++对象创建有两个步骤
1、分配空间
2、执行构造函数

l = (list)malloc(sizeof(struct Node));
你直接用malloc,相当于你只分配了内存,没有执行构造函数,使用时当然会出错了。

你可以把malloc改成new试一下
l = new Node;
------解决方案--------------------
同意楼上们的回复。记着用完后释放(delete)指针,new/delete成对使用。
------解决方案--------------------
new是C++的操作符,malloc只是分配内存用的一个函数。
虽然new封装了malloc,但还有其他的操作。new会调用构造函数,但malloc就不会。
string没有被分配内存,所以就运行错误了。
------解决方案--------------------
楼主要么彻底转C++,要么就坚持C,混用经常会遇到很多问题。
最好去看看《C++ Primer》