I am trying to do a void insertion()
, but always get a segmentation fault, see following. Same time, I referenced this link.
First, I did realloc()
, then move every memory to the next space after the position
, last put the insertion
in the position
and increase nArraySize
.
#include <stdio.h>
#include <stdlib.h>
void printArray(double array[], unsigned int size)
{
for (unsigned int i = 0; i < size; ++i)
{
printf("%.3f ", array[i]);
}
printf("\n");
}
void insert(double **array,
size_t *nArraySize,
double insertion,
unsigned int position)
{
//realloc the memory space first
*array = realloc(*array, (*nArraySize+1) * sizeof(double));
for(unsigned int i = nArraySize[0]-1; i >= position; i--)
{
*array[i+1] = *array[i];
}
*array[position] = insertion;
*nArraySize += 1;
}
int main()
{
double *t = calloc(4, sizeof(double));
t[0] = 0;
t[1] = 1;
t[2] = 2;
t[3] = 3;
size_t k = 4;
insert(&t, &k, 1, 1);
printf("k is %zu\n", k);
printArray(t, k);
free(t);
}
Please help. Any suggestion is welcome.