Allocating memory for a Structure in C

Blackbinary picture Blackbinary · Feb 1, 2010 · Viewed 91k times · Source

I'm tasked to create a program which dynamically allocates memory for a structure. normally we would use

x=malloc(sizeof(int)*y);

However, what do I use for a structure variable? I don't think its possible to do

struct st x = malloc(sizeof(struct)); 

Could someone help me out? Thanks!

Answer

dirkgently picture dirkgently · Feb 1, 2010

My favorite:

#include <stdlib.h>

struct st *x = malloc(sizeof *x); 

Note that:

  • x must be a pointer
  • no cast is required
  • include appropriate header