Reputation: 15
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.
Upvotes: 1
Views: 429
Reputation: 921
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.
Upvotes: 1
Reputation: 84551
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);
}
Upvotes: 0
Reputation: 3197
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.
Upvotes: 0
Reputation: 726509
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));
Upvotes: 3