I want to make a int* with size of 10 first and write a add() function to add elements. If the numbers of elements are bigger than 10, the function will use realloc() to resize the int*. However I got the error message. How can I improve this?
Here is what I did:
int main()
{
int size = 10;
int* a;
a = (int*)malloc(size*sizeof(int*));
int i;
double start, stop;
start = clock();
for (i = 0; i < 100000; i++){
add(&a, i, size, i);
}
stop = clock();
printf("Adding arry by one: %10.2f\n", stop - start);
return 0;
}
void add(int *a, int element, int size, int index)
{
if (index < size)
{
a[index] = element;
}
else if (index >= size)
{
a = realloc(a, sizeof(int*)*(index + 1));
a[index] = element;
}
}
void add(int*a,-->void add(int **a,,*a = realloc(*a, sizeof(int)*(index + 1));, (need update size?)reallocis done onindex(which does get upped) and notsize(which is fixed), so it's "okay" [if not optimal]int*with a size of 10. You can, however, make anint*point to a memory block with a size of 10 ints.