+crane+ 2019-08-13 11:44 采纳率: 0%
浏览 159

为啥malloc与new 差这么多?

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
struct node
{
char num[50];
char name[41];
char n[3];
char c[100];
char c1[100];
char dizhi[50];
struct node *next;
};
struct node *creat(void)
{
struct node *head,*p1,*p2;
head=NULL;  
p1=(struct node*)malloc(sizeof(struct node));
while(1)
{

scanf("%s",p1->num);
if(strcmp(p1->num,"end")==0)
break;
else
{
scanf("%s",p1->name);
scanf("%s",p1->n);
scanf("%s",p1->c);
scanf("%s",p1->c1);
scanf("%s",p1->dizhi);
p1->next=NULL;
if(head==NULL)
head=p1;
else
p2->next=p1;
p2=p1;  
p1=(struct node*)malloc(sizeof(struct node));
}


}
return head;
}
struct node *reverse(struct node *head)
{
struct node *p,*q,*t;
p=head;
q=NULL;
while(p!=NULL)
{
t=p->next;
p->next=q;
q=p;
p=t;
}
return q;
}
void print(struct node *p1)
{
struct node *p;
p=p1;
while(p!=NULL)
{   

printf("%s %s %s %s %s %s\n",p->num,p->name,p->n,p->c,p->c1,p->dizhi);
p=p->next;
}
}
int main()
{
struct node *head,*p1;
head=creat();
p1=reverse(head);
print(p1);
return 0;


}

malloc的输入版本2ms

#include<iostream>
#include<cstdio>
//#include<cstring>
using namespace std;
struct Node{
    char a[20];
    char b[40];
    char c[3];
    char d[100];
    char e[100];
    char f[40];
    Node * next,* pre;
};
Node * p,* r,* head;
int main(){
    head=new Node;
    head->next=NULL;
    head->pre=NULL;

    r=head;
    while(p=new Node,scanf("%s",p->a),p->a[0]!='e'){
        scanf("%s",p->b);
        scanf("%s",p->c);
        scanf("%s",p->d);
        scanf("%s",p->e);
        scanf("%s",p->f);
        p->next=NULL;
        p->pre=r;
        r->next=p;
        r=p;       
    }    
    while(r!=head){
        cout<<r->a<<" "<<r->b<<" "<<r->c<<" "<<r->d<<" "<<r->e<<" "<<r->f<<" "<<endl;
        r=r->pre;
    }
    return 0;
}

new 的输入版本,5ms
为啥new比malloc慢这么多

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-20 17:58
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c