繁体   English   中英

malloc不为列表的第二个元素工作

[英]malloc doesn't work for second element of list

该函数应该创建一个结构的链接列表,我在调试器中已经看到它为第一个元素分配了内存,但是在为第二个元素分配内存时,程序崩溃了。

struct Tipologia{
    int mq;
    int prezzo;
    int n;
    char descrizione[100];
};

struct Nodo{
    struct Tipologia t;
    struct Nodo *next;
};

typedef struct Nodo* NODO;

struct Tipologia creaTipologia(){
    struct Tipologia t;
    printf("MQ?\n");
    scanf("%d", &(t.mq));
    printf("PREZZO?\n");
    scanf("%d", &(t.prezzo));
    printf("DISPONIBILI?\n");
    scanf("%d", &(t.n));
    printf("DESCRIZIONE?\n");
    int c;
    while ( (c = getc(stdin)) != EOF && c != '\n');
    fgets((t.descrizione), 100, stdin);
    return t;
}

NODO costruisciPalazzo(){
    int continua;
    NODO h= NULL;
    printf("VUOI COSTRUIRE UN APPARTAMENTO? 1 SI, 0 NO\n");
    scanf("%d", &continua);
    if(continua){
        NODO n= malloc(sizeof(NODO));
        h= n;
        n->t= creaTipologia();
        n->next= NULL;
        printf("VUOI COSTRUIRE UN APPARTAMENTO? 1 SI, 0 NO\n");
        scanf("%d", &continua);
        while(continua){
            NODO nodo= malloc(sizeof(NODO));
            n->next= nodo;
            n= nodo;
            n->t= creaTipologia();
            printf("VUOI COSTRUIRE UN APPARTAMENTO? 1 SI, 0 NO\n");
            scanf("%d", &continua);
        }
        n->next= NULL;
    }
    return h;
}

我一直按照教授的指示进行操作,但是它一直崩溃,没有给出任何错误来解释实际发生的情况。 这似乎对我的同学有效,我们无法弄清楚问题出在哪里。 请帮忙

问题是您使用的typedef隐藏了NODO是指针的事实。 这很不好,因为这会造成令人困惑的情况,您期望一个类型具有一定的大小并可以使用某种语法,但是实际上这是完全不同的。

例如,您必须执行以下操作:

h= n;
n->t= creaTipologia();
n->next= NULL;

令人困惑的是, hn都没有显式声明为指针,但是您必须使用箭头符号。

我的建议是,要么完全删除typedef并在代码中使用struct nodo ,要么至少从typedef删除指针。 对其他结构进行相同操作以保持一致性:

typedef struct {
  int mq;
  int prezzo;
  int n;
  char descrizione[100];
} TIPOLOGIA;

typedef struct Nodo {
  TIPOLOGIA t;
  struct Nodo *next;
} NODO;

您还可以使用对象作为其大小的引用来简化malloc 例如:

NODO *h = malloc(sizeof *h);

这样可以避免在调用malloc时指定h的类型。 对于重用也更好。

通过执行malloc(sizeof(struct Nodo))而不是malloc(sizeof(NODO))即可解决此问题,因为使用NODO它将仅分配指针,而使用struct Nodo则分配整个元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM