scatman
scatman

Reputation: 14565

How can i Allocate Memory for a struct?

I have the following struct:

struct Node{
    int *VC;
    Node *Next;
};

My goal is to create a linked list of pointers pointing to an int

My question is how can i allocate memory for Node. ie

int* ptr = (int *) malloc(sizeof(int)*10);
//code to allocate memory for a new Node n
n->VC = ptr;
n->Next = null;   

then later i may do:

 int *_ptr= (int *) malloc(sizeof(int)*10);
 //code to allocate memory for a new Node c
 c->VC= _ptr;
 c->Next = null;

 n->Next = c;

Upvotes: 0

Views: 235

Answers (2)

timothyqiu
timothyqiu

Reputation: 1122

Allocating memory for a struct is the same as allocating memory for an int (in C). Just use sizeof to get the size of the struct:

struct Node *n = malloc(sizeof(struct Node));

Upvotes: 5

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

Node *c = malloc(sizeof(*c));

Upvotes: 3

Related Questions