Rafael Santos
Rafael Santos

Reputation: 39

Why is this C code not working?

I'm trying to insert two random strings in each node, but when I print the list the output is not correct. What can it be? I'm not good at memory allocation, so if anything is wrong please explain me. I also tried to see if a string was overwriting another, but it doesn't seem to be the case.

#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;
}

Upvotes: 1

Views: 77

Answers (2)

krpra
krpra

Reputation: 474

You did typedef struct node* node in your code.But in your functions makelist and listins_beg you have used

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

Now here *n is a pointer to struct node but it is allocating memory only 8 byte or 4 byte depending on your machine as sizeof(node*) will return 8 or 4 because node* is a pointer to pointer to a node,same things happens while allocating memory for a.It should be rather like this

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

Upvotes: 1

john elemans
john elemans

Reputation: 2676

First, as angew points out you need to get rid of

  typedef node* node;

You need to review the basics of how structures work. For example in main you declare;

    node n;

Then in mklist(..) you try to allocate the struct. But your declaration already allocated it. If you want to allocate structures, declare pointers then allocate the struct and set the pointer to point to the new memory just allocated;

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

Upvotes: 0

Related Questions