1

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

James Franco
  • 4,516
  • 10
  • 38
  • 80

1 Answers1

0
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.

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • actually it is likely to be zero if I'm not mistaken. Can you explain that it can work sometimes (when used like: `struct foo farry[]`) – Jean-François Fabre Nov 10 '16 at 07:01
  • Yeah and I read here http://stackoverflow.com/questions/15929869/count-the-number-of-elements-in-an-array-in-c that its impossible to get no of elements in array if its a pointer. I am not sure how C programmers handle a situation like this ? I mean in case of strcuture how do I create an array of 2 items ? is `malloc(2 * sizeof(struct foo)); ` even correct ? – James Franco Nov 10 '16 at 07:01
  • @JamesFranco You'll want to keep the number of `struct foo`s in `farry` in a separate variable (or separate `struct`) or use a data structure like a linked-list. Yes that's correct,, although the convention is to use `sizeof(*farry)` instead so if `farry`'s type ever changes you'll have less code to maintain. – yano Nov 10 '16 at 07:07
  • @Jean-FrançoisFabre, _it is likely to be zero_, dereferencing the pointer ([0]) gives you the size of the struct itself, compiled on my computer 8 / 8 = 1 – David Ranieri Nov 10 '16 at 07:29
  • likely if your struct is big enough, yes. – Jean-François Fabre Nov 10 '16 at 09:56