为什么我的malloc是错的 [英] Why my malloc is wrong

查看:106
本文介绍了为什么我的malloc是错的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct rec
{
    char nam[20];
    float grd;
    int id;
    struct rec *next;
};

struct rec head;
char xnam[20];
int xid;
float xgrd;


int read(struct rec happy[]);
void sort(struct rec sad[], int c );
int compare(char *ap, char *bp);
void swap( struct rec fish[], int w);

int main()
{
    struct rec what[20];
    int i=0, no=0;

    no = read(what);
    sort(what, no);

    getchar() ;
    return 0;
}


int read(struct rec info[])
{
    int l=0;

    FILE *myFile;
    myFile = fopen("student.txt", "r");


    printf("List Unsorted:\n");

    struct rec *tp;
    tp=&head;
    while (fscanf(head,"%s,%d,%f",xnam,&xgrd,&xid),myFile)
    {
        tp->next=struct rec malloc (sizeof struct rec);
        tp=tp->next;
        strcpy(tp->nam,xnam);
        tp->id=xid;
        tp->grd=xgrd;
        tp->next=NULL;
    }

    tp=head.next;
    while(head.next!=NULL)
    {
        printf("%s,%d,%f",tp->nam,tp->grd,tp->id);
    }
    fclose(myFile);

    return l;

}


int compare(char *ap, char *bp)
{
    int x = 0;
    while (ap[x] == bp[x] && ap[x] != '\0')
        x=x+1;

    if (ap[x] > bp[x])
        return 1;
    else if (ap[x] < bp[x])
        return -1;
    else
        return 0;
}


void swap( struct rec fish[], int w)
{
    int q;

    struct rec temp;

    q=compare (fish[w].nam, fish[w+1].nam);
    if (q>0)
    {
        temp = fish[w];
        fish[w] = fish[w+1];
        fish[w+1] = temp;
    }
}


void sort(struct rec cat[], int k)
{
    int y, z, c;

    for (y=0; y<k-1; y=y+1)
    {

        for (z=0; y+z<k-1; z=z+1)
        {
            swap(cat, z);
        }

    }
    printf("\nNew List\n\n");

    for (c=0; c<k; c=c+1)
    {
        printf("%s\t %d %.2f", cat[c].nam, cat[c].id, cat[c].grd);
        printf("\n");
    }
}





我尝试了什么:



i使用调试器但没有任何反应



What I have tried:

i use debugger but nothing happen

推荐答案

引用:

tp-> next = struct rec malloc(sizeof struct rec);

tp->next=struct rec malloc (sizeof struct rec);

应该是

Should be

tp->next=(struct rec *) malloc (sizeof (struct rec));


这篇关于为什么我的malloc是错的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆