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