Reputation: 15
I keep getting an error when trying to make a linked list. The error is "expected expression before 'struct'" on both of the lines where I try to malloc()
a new node. I've looked at similar questions and tried to fix my code but I can't get it to work. Any help would be very much appreciated.
#include <stdio.h>
#include <stdlib.h>
struct List {
int x;
struct List *next;
};
int main() {
struct List* head = (struct List*)malloc(sizof(struct List));
if (head == NULL) {
return 1;
}
head->x = 1;
head->next = (struct List*)malloc(sizof(struct List));
head->next->x = 2;
head->next->next = NULL;
struct List* current = head;
while(current != NULL) {
printf("%d", current->x);
current = current->next;
}
return 0;
}
Upvotes: 1
Views: 3765
Reputation: 310930
There is a typo in statements like this
struct List* head = (struct List*)malloc(sizof(struct List));
^^^^^
There must be
struct List* head = (struct List*)malloc(sizeof(struct List));
^^^^^^
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
And you should free all allocated memory for the list before exiting the program.
Upvotes: 1