I'm trying to implement dynamic array in C using realloc(). My understanding is that realloc() preserves old contents of the memory block the old pointer points to, but my following testing code suggests otherwise:
#include <stdio.h>
#include <stdlib.h>
int DARRAYSIZE=5;
typedef struct dynamicArray{
int size;
int *items;
}DArray;
int init(DArray *DAP){ //initialise the DArray
DAP->items=(int *)malloc(sizeof(int)*DARRAYSIZE);
if(DAP->items){
DAP->size=0;
return 0;
}else{
printf("Malloc failed!\n");
return 1;
}
}
void print(DArray *DAP){ //print all elements in the DArray
int i=0;
for(;i<DAP->size;i++)
printf("%d\t",DAP->items[i]);
printf("\n");
}
void add(DArray *DAP,int val){ //add the new val into the DArray
if(!full(DAP)){
DAP->items[DAP->size++]=val;
}else{
if(!grow(DAP)){
DAP->items[DAP->size++]=val;
}else
exit(1);
}
}
int full(DArray *DAP){ //returns 1 if the DAarray is full
if(DAP->size==DARRAYSIZE)
return 1;
else
return 0;
}
int grow(DArray *DAP){ //grows the DArray to double its original size
int *temp=(int *)realloc(DAP->items,DARRAYSIZE*2);
if(!temp){
printf("Realloc failed!\n");
return 1;
}else{
DAP->items=temp;
DARRAYSIZE*=2;
printf("Darray doubled and current contents are:\n");
print(DAP);
return 0;
}
}
void destroy(DArray *DAP){ //destroies the DArray
free(DAP->items);
}
int main(void){
DArray newDA;
if(!init(&newDA)){
int i;
for(i=1;i<30;i++)
add(&newDA,i);
}else
exit(1);
destroy(&newDA);
return 0;
}
What I did was print the contents of the array as soon as its size is doubled in function grow(). I compiled the code using:
:gcc -version i686-apple-darwin11-llvm-gcc-4.2
and below is the output:
with the unexpected 0's in the output.
Please kindly advise what I'm doing wrong here, thanks!
DArray
. The size of each dynamic array is independent of each other dynamic array.