Hi,
I just learned that it's possible to increase the size of the memory you'll allocate to a struct when using the malloc function. For example, you can have a struct like this:
Code:
struct test{
char c;
int v[1];
};
Which clearly has space for only 1 char and 1 int. But you could call malloc in such a way to make it hold 1 char and up to 10 ints:
Code:
int main(){
struct test *ptr;
ptr = malloc (sizeof(struct test)+sizeof(int)*9);
ptr->v[9]=50;
printf("%d\n",ptr->v[9]);
return 0;
}
The output here would be "50" printed on the screen.
My questions for the experienced C programmers out there:
1. What is happening behind the scenes here? Does the computer allocate 1+4 (char+int) bytes for the standard "struct test", and then 4*9 more bytes of memory and let the pointer "ptr" put whatever kind of data it wants on those extra bytes?
2. Does this trick only works when there is an array inside the struct?