为什么这个C代码不起作用?

时间:2018-05-25 16:38:27

标签: c list struct linked-list dynamic-allocation

我正在尝试在每个节点中插入两个随机字符串,但是当我打印列表时输出不正确。它能是什么?我不擅长内存分配,所以如果有什么不对的地方请解释一下。我还试图查看一个字符串是否覆盖了另一个字符串,但似乎并非如此。

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

struct node{
    int times;
    char name[100];
    char number[100];  
    struct node* next;
};

typedef struct node* node;

void mklist(node* n){
    *n=(node)malloc(sizeof(node*));
    (*n)->times=0;
    strcpy((*n)->name,"null");
    strcpy((*n)->number,"null");
    (*n)->next=(node)NULL;
}

void listins_beg(node* n,char name[],char num[],int tim){
    node a;
    a=(node)malloc(sizeof(node));
    if(a==NULL) exit(1);
    a->times=tim;
    strcpy(a->number,num);
    strcpy(a->name,name);
    a->next=(node)(*n);
    (*n)=a;
}

void printlist(node n){
    node x;
    x=n;
    if(x->next==NULL) printf("EMPTY LIST");
    else{
        do{
            printf("%s - %s\n",x->name,x->number);
            x=x->next;
        }while(x->next!=NULL);
    }
}

void freelist(node* n){
    node x;
    for(;x->next!=NULL;(*n)=(*n)->next){
        x=(*n);
        free(x);
    }
}

int main(void){
    node n;
    mklist(&n);
    listins_beg(&n,"Hermanouhuhuuteu","4523-2248",300);
    listins_beg(&n,"Luhu","4523-4887",299);
    listins_beg(&n,"Lulamolute","4523-4687",512);
    printlist(n);
    freelist(&n);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您在代码中执行了typedef struct node* node。但在您的函数makelistlistins_beg中,您已使用

 *n=(node)malloc(sizeof(node*));
 a=(node)malloc(sizeof(node));

现在这里*n是指向struct node的指针,但它仅根据您的计算机分配内存8 byte4 byte,因为sizeof(node*)将返回8或4因为node*pointer to pointernode,所以在为a分配内存时会发生相同的事情。它应该是这样的

 *n=(node)malloc(sizeof(struct node)); //in makelist
 a=(node)malloc(sizeof(struct node));  //in listins_beg 

答案 1 :(得分:0)

首先,正如angew指出你需要摆脱

  typedef node* node;

您需要查看结构如何工作的基础知识。例如,在main中声明;

    node n;

然后在mklist(..)中尝试分配结构。但你的声明已经分配了它。如果要分配结构,声明指针然后分配结构并将指针设置为指向刚刚分配的新内存;

  node *p;
  p = malloc(sizeof(node));