简体   繁体   中英

Swapping strings between nodes in C

I'm trying to swap the data fields between nodes in my linked list, having trouble swapping the char arrays. this is just a sample of the program.

struct node {
    int count;
    char word[50];
    struct node *next;
};

void swap_nodes( struct node *first, struct node *second ) {
    int temp_count;
    char *temp_word;

    temp_count = first->count;
    temp_word = first->word;
    first->count = second->count;
    first->word = second->word;
    second->count = temp_count;
    second->word = temp_word;
}

Let me know what I'm doing wrong, I'm very new at writing in c.

When you assign an array of characters to a pointer, you do not make a copy of the array:

char *temp_word;
temp_word = first->word;

temp_word points to the initial element of the array, so assigning to the array would change the data pointed to by the pointer as well.

You can fix this by declaring an array of 50 characters, and using strcpy or memcpy to do the copying:

char temp_word[50];
memcpy(temp_word, first->word, sizeof(temp_word));
memcpy(first->word, second->word, sizeof(temp_word));
memcpy(second->word, temp_word, sizeof(temp_word));

Well, you have already received answers, I just want to point out that you could exchange the nodes position in the list (instead the node content). As you have a single linked list, you will need the parents of the nodes to do so.

Alternatively, you can use dynamic memory instead the static array for "word", this way you only have to swap the pointers, avoiding the array copy.

The word[50] is a part of struct node , it's inside of the struct node , while what you have done is just move a pointer *temp_word point to *first , then to *second , the content of the word[50] is not changed in deeply. you can use memcpy to change the contents.

An appropriate implementation with strncpy and strdup would be:

#include <string.h>

void swap_nodes( struct node *first, struct node *second ) {
    int temp_count;
    char *temp_word;

    temp_count = first->count;
    temp_word = strdup (first->word);
    first->count = second->count;
    strncpy (first->word, second->word, 50);    /* 50 based on struct definition       */
    second->count = temp_count;                 /* could be ( strlen (temp_word) + 1 ) */
    strncpy (second->word, temp_word, 50);

    if (temp_word)                              /* free memory allocated with strdup   */
        free (temp_word);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM