I want to create a linked list in C in which the user can input strings which will be stored as nodes in the list. This is my node structure:
typdef struct NODE {
char word[50];
struct NODE* next;
} node;
From my main method I want to prompt the user to enter a strings and subsequently call a method that adds the string to the linked list (but does not include any characters following a space), and do that repeatedly until the user enters a specific string which terminates the process, so in my main method I have:
void main(){
node* fullList = NULL;
char stopString[5];
sprintf(stopString, "stop");
char string[50];
printf("Enter a word: ");
scanf("%[^ ]s", string);
while (strcmp(string, stopString) != 0) {
addToLinkedList(fullList, string);
printf("Enter a word: ");
scanf("%[^ ]s", string);
}
}
This is my addition method:
void addToLinkedList(node* list, char str[]) {
node* freeSpot;
node* newNode;
freeSpot = list;
if (list == NULL){
freeSpot = freeSpot->next;
}
newNode = (node *)malloc(sizeof(node));
newNode->word = str;
//strcpy(nweNode->next, str);
newNode->next = NULL;
freeSpot->next = newNode;
}
BUT I get an error:
"incompatible types when assigning to type âchar[256]â from type âchar *â"
and if I replace "newNode->word = str;" with the piece of code commented out below, I get:
warning: passing argument 1 of âstrcpyâ from incompatible pointer type [enabled by default]
/usr/include/string.h:128:14: note: expected âchar * __restrict__â but argument is of type
âstruct NODE *â
I'm pretty stuck at this point, I'm not sure how to implement this successfully; any suggestions?
if (list == NULL){-->while(freeSpot->next != NULL){s, this is finescanf("%s", string);%sstops reading after a space character is read. Also note that since you are not allocating new memory for your string inputs, all strings in the list will contain the same valuevoid addToLinkedList(node* list, char str[]) {-->void addToLinkedList(node** list, char str[]) {if(*list == NULL) { *list = newNode;}