Thursday, September 16, 2010

Where is ZERO size array is used?

If you normally try to declare a zero size array, you would end of getting array, but if the same is used as the last element of a structure then it does not give any error. Infact its method or trick to use variable size array for the last element, this can be achived as shown in the below program.

#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct 
{
    int d;
    char name[0];
}s;

int main(void)
{
    char str[] = "prasad";
    int len;
    s *s1;
    len = strlen(str);
    s1 = (s *)malloc(sizeof(*s1) + len + 1);
    strcpy(s1->name, str);
    s1->d = 12345678;
    printf("d : %d  name : %s", s1->d, s1->name);
}

This kind of trick is normally not required, and you can program most of the things in this world with out using this, but still some people want to show that they can do something special than everybody, so they can do this trick, but when you do this you must be extra careful as you need to allocate right amount of memory for the variable size array, else you would end of corrupting others memory.

No comments:

Post a Comment