malloc改成new,指针悬空C语言

从网上csdn博客搜到了一个群,里面的人提示我指针悬空了,还建议我把malloc改成new。他亲切地发出了下面的程序。为我调试过。从内容看,它的用语简明,又高手只用最小的代码调试错误的风范。
在这里插入图片描述

后来广州粉丝教我new应该怎么用。我得到了正确的程序结果。下面注释的部分是我调试时注释的。我加上了new那句。我一开始根本不知道new是什么东西,要放在哪里。

群主还自我介绍来自北京。还有大量的电子资料再在群文件。我如获至宝。感觉很亲切。

#include

#include

#include

using namespace std;

typedef struct data

{

int number;

string name;

string sex;

}data;

typedef struct listpoint

{

data *information;

listpoint *next;

listpoint *last;

listpoint *branch;

}listpoint;

/********************************************************/

listpoint *create_normal_list(int n)

{

listpoint *head,*normal,*end;

// head=(listpoint*)malloc(sizeof(listpoint));

head=new listpoint;



// head->information=(data*)malloc(sizeof(data));

head->information=new data;

end=head;

for(int i=0;i<n;i++)

{

   // normal=(listpoint*)malloc(sizeof(listpoint));

   normal=new listpoint;

    // normal->information=(data*)malloc(sizeof(data));

    normal->information=new data;



    cout<<"input the number :";

    cin>>normal->information->number;

 cout<<"input the name   :";

        cin>>normal->information->name;

    cout<<"input the sex    :";

    cin>>normal->information->sex;

    cout<<"----------------------------------"<<endl;

    end->next=normal;

    normal->last=end;

    end=normal;

}

end->next=NULL;

head->last=NULL;

return head;

}

listpoint *create_random_branch_list(int n)

{

listpoint *search_point(listpoint *list,int n);

listpoint *head;

head=create_normal_list(n);

listpoint *p,*bp;

p=head;

srand((int)(time(NULL)));

int randnum;

while((p=p->next)!=NULL)

{

    randnum=rand()%n+1;

    bp=search_point(head,randnum);

    p->branch=bp;

}

return head;

int main()

{

listpoint *head;

head=create_random_sort_list(2);

system("pause");

return 0;

}

运行结果:
在这里插入图片描述

作者:千条数学课收藏夹分类
https://www.bilibili.com/read/cv7049937
出处: bilibili

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值