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;
}
In C, array names are non modifiable lvalues. You cannot assign anything to an array variable. Hence, you are getting error on this statement:
array = insert(&array[0], value, NUM(array), NUM(array)+1);
new_array
is a pointer and remember arrays and pointers are different. When you access an array, it is converted to a pointer to first element (there are few exceptions to this rule)1).
Also note that
int array[] = {1};
the size of array array
is 1
. When you omit the dimension of an array, compiler deduce it based on the size of initialiser and you are initialising array
with only one element. So, the array array
is an array of one int
type element.
That means, this
int array[] = {1};
is same as this
int array[1] = {1};
You are passing NUM(array)+1
to insert()
function and accessing array
element at pos
index, where pos
value is NUM(array)+1
, i.e. accessing array beyond its size, which is an undefined behaviour.
Also, you should not use void
as return type of main()
function . As per C language standards, the return type of main()
function should be int
.
3 Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. ....