Reputation: 79
I was browsing SO and found some code that raised a question for me.
struct node* BuildOneTwoThree() {
struct node *list = malloc(3 * sizeof(struct node));
list[0].data = 1;
list[0].next = list+1;
list[1].data = 2;
list[1].next = list+2;
list[2].data = 3;
list[2].next = NULL;
return list;}
I'm trying to understand how this call to malloc works and what it returns. Did it return an array of pointers? How does that work out, I didn't expect malloc to work in this way?
This seems to guarantee that the memory indices of the individual structs are one after another which I imagine could be a powerful or useful tool.
Also after such a call to malloc would it be okay to initialise the array indices as
list[0] = (struct node) {1, list +1};
Note: struct node is defined as,
struct node{
int data;
struct node *next;};
Upvotes: 0
Views: 70
Reputation: 1180
struct node *list = malloc(3 * sizeof(struct node));
==> created a memory of three node structure size and list is pointed to the beginning of the memory storage. It means list=&list[0] or *list = list[0], list+1=&(list[1]) or *(list+1)=list[1], list+2=&(list[2]) or *(list+2)=list[2]
list[0] = (struct node) {1, list +1};
==> Yes, you can do that way. Here is my modification as that way, it worked fine:
struct node* BuildOneTwoThree() {
struct node *list = (struct node *)malloc(3 * sizeof(struct node));
list[0] = { 1, list + 1 };
list[1] = { 2, list + 2 };
list[2] = { 3, NULL };
return list;
}
Upvotes: 1
Reputation: 1841
malloc
returns a pointer to a memory region with the specified size.
The argument 3 * sizeof(struct node)
says the region size is able to store 3 node
structures.
Pointers and indices in arrays are interchangeable, as discussed in this answer.
Upvotes: 1