Wednesday, 11 May 2016

How to allocate the dynamic char array without using char pointer in struct?

 

Solution: By the struct hack technique

struct s
{
char a[0];
};

When allocating memory for struct allocate a memory for char array too.

struct s *ptr=(s*)malloc(sizeof(s)*10); //char array with 10 bytes


1.       Reason for using struct hack is memory will be allocated in linear way along with structure memory.