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


this question has answer here:

i have been programming in c++ while learning c. trying following code trying understand behaviour of realloc strcture

struct foo{ int a; int b; }; 

and how using it.initially want create array of size 2. (which manage do). increase size of same array 3 preserving previous content use realloc . 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 size of array \n");  //increase size   int oldsize = sizeof(farry)/sizeof(farry[0]);  farry = realloc(farry, (oldsize+1) * sizeof(struct foo));  printf("new size %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 output get

value 1  value 2  -----increasing size of array  new size 1  value 1  value 2 

i expecting new size 3 , printing 1,2,3 new size 1 why ? old size , new size same in above case.i appreciate if explain might missing or doing wrong

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

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


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -