Reputation: 23
code1
#include "header.h"
#define MAX_BUFFER 100
typedef struct node node_t;
typedef struct node{
int data;
node_t* next;
}node_t;
node_t* head = (node_t*)malloc(sizeof(node_t));
....
void insert(node_t** first, int n);
code 2
#include "header.h"
#define MAX_BUFFER 100
typedef struct node node_t;
typedef struct node{
int data;
node_t* next;
}node_t;
node_t* head = NULL;
void insert(node_t** first, int n);
...
void insert(node_t** first, int n)
{
node_t* new_node = (node_t*)malloc(sizeof(node_t));
}
When I compile code 1, the error occurs and it says
llist.c:10:16: error: initializer element is not a compile-time constant
node_t* head = (node_t*)malloc(sizeof(node_t));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
And code2, no error occurred.
I don't get the meaning of compile-time constant. Can anyone please explain me why in code 1 error occurs?
Upvotes: 0
Views: 113
Reputation: 12668
Of course initializing a global variable with a call to a function requires to execute code to initialize it, which is not possible at load time, as global variable initializer values are already encoded in the loaded file, as the initialized .data
section (this is the reason for the initializers to need to be constants) A call to a function is never a constant expresion, it's return value is a pointer, dependent on the internal state of the malloc()
library, so it cannot be encoded in the executable file as some fixed value.
But you can initialize it to NULL
, and then test at some point if its value is NULL
, then initialize it. But always after some code has been executed.
Upvotes: 1
Reputation: 15793
At top-level you cannot initialize with malloc
.
At top-level you need to use only static data, for example,
node_t head = { ... };
and you fill with static initializers, like { some_int, NULL}
or { some_int, &other_static_node }
. Or something like:
node_t *head = NULL;
and you initialize head
using head = malloc(sizeof(node_t));
from an initialization function. Note, I do not cast the output of malloc
.
Upvotes: 2