James Franco James Franco - 1 month ago 16
C Question

Using realloc in this code - Size of my array not increasing

I have been programming in C++ for a while however I am just learning C.
I was trying the following code trying to understand the behaviour of realloc
This is my strcture

struct foo{
int a;
int b;
};


and this is how I am using it.Initially I want to create an array of size 2. (Which I manage to do). Then I would like to increase the size of the same array to 3 preserving its previous content so I use realloc . This is my code

//Create array of size 2
struct foo* farry = malloc(2 * sizeof(struct foo));
farry[0].a =1;
farry[1].a =2;
for(i=0 ; i<=(sizeof(farry)/sizeof(farry[0])) ; i++)
{
printf("Value %d \n",farry[i].a );
}


printf("-----Increasing the size of the array \n");
//Increase the size
int oldsize = sizeof(farry)/sizeof(farry[0]);
farry = realloc(farry, (oldsize+1) * sizeof(struct foo));
printf("new size is %d \n",sizeof(farry)/sizeof(farry[0]) );
farry[2].a =3;
for(i=0 ; i<=(sizeof(farry)/sizeof(farry[0])) ; i++)
{
printf("Value %d \n",farry[i].a );
}


This is the output that I get

Value 1
Value 2
-----Increasing the size of the array
new size is 1
Value 1
Value 2


I was expecting new size to be 3 and printing 1,2,3 but its new size is 1 why is that ? The old size and new size are the same in the above case.I would appreciate it if someone could explain what I might be missing or doing wrong

Answer
struct foo* farry = malloc(2 * sizeof(struct foo)); 
...
int oldsize = sizeof(farry)/sizeof(farry[0]);

sizeof(farry)/sizeof(farry[0]) gives you the size of a pointer / size of the struct, not the number of elements.