I'm trying to write a dynamic array in C and I almost did it.Now I' stuck at a point where it gives error while inserting in that error using realloc().Here is my code:
#include<stdio.h>
#include<stdlib.h>
typedef struct {
int *array;//pointer that points to the start of the contiguous allocated blocks(an array of int)
size_t used;//array used
size_t size;//array total size
}D_Array;
void alloc_array(D_Array *a, int initial_size)
{
//allocate contiguous memory blocks and point a pointer to its beginning address...
a->array = (int*)malloc(initial_size*sizeof(int));
a->used = 0;
a->size = initial_size;
}
void insert_array(D_Array *a, int element)
{
if(a->used == a->size)
{
//allocate one more space and then insert in array
a->array = (int*)relloc(a->array,(a->size)*sizeof(int));
}
a->array[a->used++] = element;
}
void free_array(D_Array *a)
{
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
int main()
{
D_Array a;
int i=0, initial_size=0, insert_element=0;
printf("Enter the initial size of array :");
scanf("%d",&initial_size);
alloc_array(&a, initial_size);
printf("\nEnter the elements to be inserted initially");
for(i=0 ; i<initial_size ; ++i)
{
scanf("%d",&insert_element);
insert_array(&a, insert_element);
}
a.array[0] = 3;
for(i=0 ; i<initial_size ; ++i)
{
printf("%d",*((a.array)+i));
}
}
Problem is in method "insert_array" but I don't know why.Everything seems fine to me.
[update from comment:]
The compiler gives:
quicksort.c:32:14: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] a->array = (int*)relloc(a->array,(a->size)*sizeof(int)); ^ /tmp/ccXTwlHh.o: In function insert_array': quicksort.c:(.text+0x8d): undefined reference to relloc' collect2: error: ld returned 1 exit status
Adding to what's been said, you've written relloc
instead of realloc
. So there is perhaps a typo which is hindering the compilation.