user3023835
user3023835

Reputation: 13

how to insert a string in a linked list inserting function

I want to insert a string into struct data_node in a function called insert. My struct data_node is

struct data_node {
   char name [25];
   int data;
   struct data_node *next;
   };

and my insert function is:

struct data_node * insert (struct data_node **p_first, int elem, char *word ) {

    struct data_node *new_node, *prev, *current;
    current=*p_first;
    while (current != NULL && elem > current->data) {
       prev=current;
       current=current->next;
    } /* end while */

    /* current now points to position *before* which we need to insert */
    new_node = (struct data_node *) malloc(sizeof(struct data_node));
    new_node->data=elem;
    new_node->name=*word;

    new_node->next=current;
    if ( current == *p_first ) /* insert before 1st element */
       *p_first=new_node;
    else                       /* now insert before current */
       prev->next=new_node;
    /* end if current == *p_first */
    return new_node;
};

when I compile , it says that the line 22 incompatible types when assigning to type 'char[25]' from type 'char' that means new_node->name=*word; is wrong. how could I solve this problem?

Upvotes: 0

Views: 1862

Answers (3)

Beta
Beta

Reputation: 99094

The linked list structure is irrelevant. This problem boils down to copying one char[] to another. This will work:

strncpy(new_node->name, word, 25);

with some caveats. If word doesn't point to a valid char[], then this could cause undefined behavior. If it points to an array containing more than 25 25 or more (non-null) characters, the operation will copy the first 25 into new_node->name, which means that new_node->name will not be null-terminated, which could cause trouble later if other code assumes that it is. As WhozCraig points out, it's almost always a good idea to terminate the destination string with a null -- after being sure to leave room for it by copying one less character than you could (i.e. 25-1). And you might consider defining a constant NAMELENGTH so that you don't have the magic number 25 appearing here and there in your code.

Upvotes: 1

You should use the strcpy method to copy word value in new_node -> name.

Take a look at this link.

strcpy(new_node->name, word);

Upvotes: 0

David Andreoletti
David Andreoletti

Reputation: 4861

data_node.data should be void *. This way you can store any type (though you will have to know what type it is when reading it).

Upvotes: 0

Related Questions