I have a newbie question regarding array and functions in C.
Let's say I have this array:
int array1[10] = {2,4,6,3,2,3,6,7,9,1};
I wrote this function:
int *reverseArray(int *array, int size)
{
int *arr = malloc(size * sizeof(int));
int i, j;
for(i = 10, j = 0; i > 0; i--, i++) {
arr[j] = array[i];
}
return arr;
}
I don't even know if it works, because if I do:
array1 = reverseArray(array1, 10);
I got the error:
assignment to expression with array type
How do I assign the adress of an array to another array?
The function is correct*, and it works fine. The problem is that you cannot assign an array like this:
reverseArray
returns a pointer, so you should assign it to a pointer variable:If you want the data to be placed back in
array1
, usememcpy
:Note that since your function uses
malloc
to allocate its return value, the caller needs to deallocate this memory after it is done with it. You need to callfree(reversedArray1)
to ensure that the allocated array does not create a memory leak.* Use
size-1
in place of 10 in thefor
loop header, since you are passing it anyway, and allowi
to reach zero: