can someone tell me how to use realloc to properly extend calloc?
my expectation: all 20slots to have value of 0.
Outcome: only calloc slots have value of 0, the one I allocate with realloc have random number. output picture
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr;
int i;
int n =10;
ptr = (int*)calloc(n, sizeof(int)); //first time allocate with calloc
ptr = (int*)realloc(ptr,2*n*sizeof(int)); //extend with realloc
for(i=0;i<2*n;i++){
printf("ptr[%d]: %d \n", i, ptr[i]);
}
return 0;
}
NOTE: before anyone ask why don't I just use calloc(20,sizeof(int));
. This is not the real program that I am writing, this is just a short demo so people can see my problem easier. I actually intent to extend calloc much later in the program.
My attempt to find the answer before creating this question. I had google this:
- How to realloc properly?
- How to extend Calloc?
- How to use realloc with calloc?
- calloc() and realloc() compiling issue
- several similar to the above.
But I seem to can't find the real answer to this(I might missed it, I'm really sorry). Most of the answer that I got is that they use realloc to extend calloc just like I did, but that is exactly my problem. sorry for bad English.