| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 961 人关注过本帖
标题:关于malloc的困惑
取消只看楼主 加入收藏
a861268448
Rank: 1
等 级:新手上路
帖 子:47
专家分:0
注 册:2014-9-15
结帖率:66.67%
收藏
已结贴  问题点数:16 回复次数:3 
关于malloc的困惑
代码如下

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct student
{
    int num;
    int score;
    struct student * next;
};
typedef struct student STU;
STU *create(void)
{
    STU*head=NULL;
    STU*tail=NULL;
    head=(STU*)malloc(sizeof(STU));
    if(head==NULL)
    {
        printf("头结点内存申请失败");//什么情况会失败
        return NULL;//不理解
    }

    head->next=NULL;
    tail=head;
    STU*pnewelement=NULL;
    int n,s;
    while(1)
    {
        printf("请输入学号和成绩\n");
        scanf("%d%d",&n,&s);
        if(n>0 &&s>0)
        {
            pnewelement=(STU*)malloc(sizeof(STU));
            if(pnewelement==NULL){
                printf("头结点内存申请失败");
                return NULL;
            }
            pnewelement->num=n;
            pnewelement->score=s;
            pnewelement->next=NULL;
            tail->next=pnewelement;
            tail=pnewelement;
        }
        else
            break;
    }
    pnewelement=head;
    head=head->next;
    free(pnewelement);
    return head;
}
void disp(STU *head)
{
    STU*p=head;
    while(1)
    {
        if(p==NULL)
        return;
        printf("(学号:%d,成绩:%d)\n",p->num,p->score);
        p=p->next;
    }
}
void main(void)
{
    STU* head=NULL;
    head=create();
    disp(head);
    getch();
}

困惑:
1、什么时候会申请失败呢?
2、为什么要return null;
  百度到说是返回一个空地址 即0x00000000,,返回的意义是什么?
  以及我也不太懂一些程序中返回 return 0;的意义
搜索更多相关主题的帖子: include return create 
2015-03-15 23:22
a861268448
Rank: 1
等 级:新手上路
帖 子:47
专家分:0
注 册:2014-9-15
收藏
得分:0 
回复 2楼 lxmaint
那什么时候return 0;
什么时候return NULL;呢
2015-03-16 17:25
a861268448
Rank: 1
等 级:新手上路
帖 子:47
专家分:0
注 册:2014-9-15
收藏
得分:0 
回复 7楼 TonyDeng
对于你说的第4点没有搞明白,我创建的这个链表在存储数据的过程中,不是先创建第一个吗?所以我觉得判断head就好了
2015-03-16 18:54
a861268448
Rank: 1
等 级:新手上路
帖 子:47
专家分:0
注 册:2014-9-15
收藏
得分:0 
回复 10楼 TonyDeng
嗯,我刚刚说的的确有问题,但是这个代码后面不是对每个都判断了吗?
 pnewelement=(STU*)malloc(sizeof(STU));
            if(pnewelement==NULL){
                printf("头结点内存申请失败");
                return NULL;
            }
            pnewelement->num=n;
            pnewelement->score=s;
            pnewelement->next=NULL;
            tail->next=pnewelement;
            tail=pnewelement;
2015-03-16 20:54
快速回复:关于malloc的困惑
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011487 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved