I read a 26 page explanation online about linked lists from Stanford university, actually I read it about 100 times and I understood it in the end.
So I copied the code and got it working fine. However, that tutorial and every tutorial online only looks at ints inside structures, it never looks at strings.
I tried to modify the code to get it working with strings but I've got stuck.
Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
char strname[5];
struct node* next;
};
void Push (struct node** headRef, char* name);
int main()
{
struct node* head = NULL;
char name[5]="Paul";
Push(&head,name);
struct node* current = head;
while (current !=NULL)
{
printf("%s", current->strname);
current = current->next;
}
}
void Push(struct node** headRef, char* name)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->strname= *name;
newNode->next = *headRef;
*headRef = newNode;
}
The error I keep getting is about incompatible types in assignment
Code:
newNode->strname= *name
. The only incompatibility is that one points to an array inside a structure and the other just points to an array.
Now I suspect the problem is that unlike integers, you can't copy arrays as easy as a=b, and instead you have to use strcopy. But I don't know how to implement it here.
Even so, I read my code as: create an array called name of 5 characters and assign it "Paul". Include the address of this array as an argument in the Push call function and in the called function point to it. Then, whatever name points to, which is "Paul", copy it to strname in the structure.
Obviously there must be many things I am missing, which is why every tutorial just shows the simple linked list of integers only.