Reputation: 331
I am working on an exercise where this is a piece of the code:
typedef struct node
{
size_t size;
struct node *next;
} node_t;
byte heap[SIZE];
node_t *node_list;
void heap_init()
{
node_list = (node_t*) heap;
node_list->size = SIZE;
node_list->next = NULL;
}
But i have some trouble under standing the line:
node_list = (node_t*) heap;
Upvotes: 3
Views: 75
Reputation: 3361
It seems the code you are pointing to is using a less common method of allocating memory i.e. as byte array.. instead of a common method of malloc or calloc
Now
node_list = (node_t*) heap;
All one can infer from this line is since heap is a byte array here, and
node_list which is a pointer to struct node type is pointing to the starting address of your byte array named heap and since the pointer would be byte* type it is typecasted to struct node* type.
One can infer it just like struct node * ptr = (struct node*) malloc(sizeof(struct node));
here (struct node*) is used in front of malloc(sizeof(struct node)); to typecast void type of pointer returned by malloc to match the required struct node type on left side of '=' equal sign.
hope it helps :)
Upvotes: 1
Reputation: 62542
The code is using the memory allocated for heap
to store a node_t
instance in, rather that allocate it using one of the malloc
school of functions functions.
The variable heap
on its own degraded to a pointer to byte*
and the code says "I want to reinterpret the byte*
as a node_t*
pointer".
Note that for this to work the value SIZE
must be at least sizeof(node_t)
, otherwise the node_t
instance won't fit within the heap
variable.
Upvotes: 1
Reputation: 8614
heap
is an array of bytes of size SIZE
.
node_list
is a pointer of type node_t
. This pointer is assigned to the first byte of the array heap
. What this does is that node_list
is assigned to an allocated location of memory.
I am guessing that the next pointer for the list will be assigned to a location further along this array.
This is most probably simulating a heap in the global variables, and avoids the use of malloc
which cannot be used some embedded systems.
Upvotes: 3