Reputation: 1
I've recently been getting into C. A project I'm currently working on requires the use of a linked list, so I sourced some boilerplate code. This code seems to be fairly standard, recurring on multiple sites. I however cannot seem to get it to work.
typedef struct node {
int value;
struct node * next;
} node_t;
node_t * head = NULL;
head = (node_t *)malloc(sizeof(node_t));
Results in the error messages
main.c:7:1: warning: type specifier missing, defailts to 'int'
head = (node_t *)malloc(sizeof(node_t));
^
main.c:7:1: error: redefinition of 'head' with a different type: 'int' vs 'node_t *' (aka 'struct node *')
main.c:6:10: note: previous defintion is here
node_t * head = NULL;
^
To me this looks like head failed to initialize as node_t *, and defaulted to an int. Why would this happen? How would you solve this? In case it matters im using Repl.it with clang-7.
Upvotes: 0
Views: 43
Reputation: 14157
In old times C compilers let use functions without declaring them. Their return value defaults to int. You missed include of stdlib.h thus malloc is undeclared and returns int.
Upvotes: 0
Reputation: 60097
You can't have assignments (statements) in filescope. Put the malloc
call in a function.
You might want to remove the (node_t*)
cast too. It's bad practice in C, as it can hide a lack of malloc
declaration (=> the file should include stdlib.h
to get that declaration).
#include <stdlib.h>
typedef struct node {
int value;
struct node * next;
} node_t;
node_t * head = NULL;
int main(void)
{
head = malloc(sizeof(*head));
}
(To avoid conflicts with POSIX, you might also want to avoid names ending with _t
: http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html.)
Upvotes: 0
Reputation: 67721
In C language all the code has to be in the function bodies.
#include <stdlib.h>
typedef struct node {
int value;
struct node * next;
} node_t;
node_t * head = NULL;
void foo(void)
{
head = malloc(sizeof(*head));
}
Upvotes: 1