typedef struct dlistclient{
int x,y;
CString name;
CString address;
struct dlistclient *prior,*next;
}DListClient;
typedef DListClient *DLinkList;
DLinkList listhead;void CMainFrame::creatlist()
{
  DListClient *s=new(DListClient);//=malloc(sizeof(DListClient));
 // s=(DListClient *)malloc(sizeof(DListClient));
   s->x=10;
  s->name=strname;
  if(listhead==NULL)
  {
  listhead=new(DListClient);
  }
  listhead->next=s;
  s->prior=listhead;
  listhead=s;
}书上
   s=(DListClient *)malloc(sizeof(DListClient));
   s->x=10;
   s->name=strname;
在实际编程中 s->x=10;执行没问题,
             s->name=strname;
错误提示:
            提示
Unhandled exception in newsrtuct.exe(MFC42D.DLL):0xC000005:Access Violation但是现在改成DListClient *s=new(DListClient);一切OK请问原因何在????

解决方案 »

  1.   

    new和malloc的区别就在于一个执行了构造函数,另一个没有。象上面一样,如果你用了malloc,只是为name分配了一个内存空间,但是没有在这上面构造一个CString对象。
      

  2.   

    在new 你的结构的时候调用的CString 的构造函数,为CString的成员准备好了内存,但是malloc中却没有调用构造函数.
    所以,你的这种编程习惯最好成为大家的警示.如果使用了c++,最好不用用c的函数.否则容易产生错误
      

  3.   

    用new把
    因为new才让构造函数首先执行
    malloc不会让构造函数执行的
    你的结构体定义的CString
    如果不经过构造函数
    肯定会出问题
    如果一定要用malloc
    改成  char* xxxx动态分配内存
    或者  char xxx[yyy]预指定