C arrays and functions, how to return?

71 views Asked by At

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?

1

There are 1 answers

3
Sergey Kalinichenko On BEST ANSWER

The function is correct*, and it works fine. The problem is that you cannot assign an array like this:

array1 = reverseArray(array1, 10);

reverseArray returns a pointer, so you should assign it to a pointer variable:

int* reversedArray1 = reverseArray(array1, 10);

If you want the data to be placed back in array1, use memcpy:

memcpy(array1, reversedArray1, sizeof(array1));
free(reversedArray1);

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 call free(reversedArray1) to ensure that the allocated array does not create a memory leak.

* Use size-1 in place of 10 in the for loop header, since you are passing it anyway, and allow i to reach zero:

for(i = size-1, j = 0; i >= 0; i--, j++)