Search code examples
clinked-listcharstrcpylow-level

C: Retrieving char value from linked list


I've been tampering with linked lists that is storing values of type char array. The issue I'm having is retrieving the value to be stored in another char that will be used for display.

I've tried using (example):

char display*;
node * data = <method to retrieve data as node *>

strcpy(display, data->value); 

This gives me warning: "passing argument 2 of ‘strcpy’ makes pointer from integer without a cast" pointing to data.

sprintf(display, "%s", data->value);

This gives me warning:

"format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’"

pointing to data->value and suggesting I used %d instead.

At the moment if I compile the first letter is showing but the rest are tiny squares/characters.

What am I doing wrong?

Thanks

[Edit]

This is the initialisation of the struct:

typedef struct node_list {
    char value;
    struct node_list * next;
} node;

This is push:

void push(char *value) {
    node_list* n = (node*)malloc(sizeof(node));

    n->value = *value;
    n->next = head;
    head = n;
}

[Edit 2]

Fixed Sorry for the waste of time. Guide I was following has apparently mistakes in it as it declared the struct with char value instead of char value[10] (for example.)


Solution

  • You are passing your push function a string, but only storing the first character of it in your list node. If you want to store the whole string, you're going to need to make a few changes.

    Firstly, you need to change value to be a char * in your structure.

    typedef struct node_list {
        char *value;
        struct node_list * next;
    } node;
    

    and in your push function you need to make a copy of the string to store it in the node.

    n->value=malloc(strlen(value)+1); // allocate memory to store the new string plus 1 extra for the null terminator
    strcpy(n->value, value); // copy the string
    

    you will need to remember to free that extra memory when you come to destroy the list later.

    This still won't completely fix the code you originally posted as display is an uninitialised pointer so you can't just strcpy or sprintf to it. You'd either need to allocate enough memory for it like I've done above in push or you could just assign the value to display since judging by the name, you're only going to display it.

    Or maybe not even bother with display at all and just use the value from the node as is. The following will work just fine...

    node * data = <method to retrieve data as node *>
    printf("Node value is %s\n",data->value);