Emanuel Emanuel - 2 months ago 10
C Question

C list->data doesnt show on terminal

The console doesnt show the data from my list node.I filled it with chars that i took from a text File.

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

struct list_node{
char data;
struct list_node* next;
};

typedef struct list_node* node;

node insert_right(node list,char data)
{
node new_node = (node) malloc(sizeof(struct list_node));
new_node->data = data;
new_node->next = list->next;
list->next = new_node;
return new_node;
}

int main()
{
FILE *fr = fopen("dat1.txt","r");
node list = (node) malloc(sizeof(struct list_node));
int i;

while((i = fgetc(fr)) != EOF){
insert_right(list,i);
}
printf("%c",list->data);
}


The main problem i think would be in the insert method.

Answer

You are allocating memory to a node called list, but yet you do not initialize any value for data, it can be garbage or any character that does not show up in the console.

When you insert a new value, a new node is created and the first one, the "head" so to speak, is still uninitialized even though it is pointing to a second node that has a meaningful data there.

This is your list:

// Node Y (X) indicates the Y-th node that has a X value.

Node1 (garbage) -> Node2 (value) -> Node3 (value) -> garbage

The last node of your list (which is also the first when you create it) should be pointing to NULL instead of being uninitialized.

I am also pretty sure that your list is poor-implemented because the new elements are always being pointed by list, so you lose track of the ones you created before.

Here is a better version, in my opinion:

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

struct list_node{
    char data;
    struct list_node* next;
};

typedef struct list_node* node;

void insert_right(node list,char data)
{
    node new_node = (node) malloc(sizeof(struct list_node));

    node temp = list;
    // It runs through the list until it reaches the last node
    while(temp->next != NULL) temp = temp->next;

    temp->data = data; 
    temp->next = new_node;
    new_node->next = NULL;
}

int main()
{
    FILE *fr = fopen("dat1.txt","r");

    // List points to only the first element of the list.
    node list = (node) malloc(sizeof(struct list_node));
    list->next = NULL;
    int i;

    while((i = fgetc(fr)) != EOF){          
            insert_right(list,i);                   
    }
    while(list != NULL) {
      printf("%c",list->data);
      list = list->next;
    }
} 
Comments