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.
CodePudding user response:
These statements are incorrect due to the operator precedence.
*array[i 1] = *array[i];
*array[position] = insertion;
That is postfix operators have a higher precedence than unary operators.
You have to write either
( *array )[i 1] = ( *array )[i];
( *array )[position] = insertion;
or as you are already doing like
array[0][i 1] = array[0][i];
array[0][position] = insertion;
Pay attention to that your function insert is unsafe because there is no check whether the value of position is less than or equal to the current number of elements in the passed array.
Also this for loop
for(unsigned int i = nArraySize[0]-1; i >= position; i--)
{
( *array )[i 1] = ( *array )[i];
}
can invoke undefined behavior. First of all the variable i
has always a non-negative number. That is the value of i
can not be negative because the variable i
has the type unsigned int
. Now let's assume that *nArraySize
is equal to 1
and position
is equal to 0
; In this case you have the loop
for(unsigned int i = 0; i >= 0; i--)
{
( *array )[i 1] = ( *array )[i];
}
and after the first iteration of the loop the value of i
will be very big that is greater than 0
.
So it will be better to rewrite the loop the following way
for(unsigned int i = *nArraySize; i > position; i--)
{
( *array )[i] = ( *array )[i-1];
}