I would like to insert value into the array's last position. So, I created the function insert. This function returns the new array.
In this code, I would like to insert value=0 into array={1}'s last position and assign the new array to an array I declare at the beginning of the main.
So I wrote:
array = insert(&array[0], value, NUM(array), NUM(array)+1)
However, I received the error:
ERROR: assignment to expression with array type` in the line:
`array = insert(&array[0], value, NUM(array), NUM(array)+1);
but if I declare a new_array this error does not occur.
I would like to know why this occurs and how to solve it.
Thanks.
#include <stdio.h>
#define NUM(a) (sizeof(a) / sizeof(*a))
int * insert(int *, int, int, int);
void main(){
int array[] = {1};
// int *new_array;
int value = 0;
int num = 3;
int pos = 2;
array = insert(&array[0], value, NUM(array), NUM(array)+1);
int i;
for(i = 0; i < NUM(array); i++) {
printf("array[%d] = %d\n", i, array[i]);
}
}
int * insert(int *p, int a, int N, int pos){
int i;
// // now shift rest of the elements downwards
// for(i = N; i >= 0; i--) {
// p[i+1] = p[i];
// }
// increase the size by 1
N++;
// shift elements forward
for (i = N-1; i >= pos; i--)
p[i] = p[i - 1];
// insert x at pos
p[pos - 1] = a;
return p;
}
ais an array, you cannot doa = .... You need to doa[i] = ....