0

I somehow can not return a int[] from my function I wrote in the code below. Can anybody explain why I am doing it wrong, instead of only posting a code solution .

Why can't I square all values and set arr = square_all(arr)?

#include <stdio.h>

void print(int arr[])
{
    for(int i = 0; i <= sizeof(arr) / sizeof(int); i++)
    {
        printf("%i", arr[i]);
    }
}

int* square_all(int arr[])
{
    for(int i = 0; i <= sizeof(arr) / sizeof(int); i++)
    {
        arr[i] = arr[i] * arr[i];
    }

    return arr;
}

int main()
{
    int arr[] = {1, 2, 3};
    print(arr);
    arr = square_all(arr);

    return 0;
}
maistai
  • 35
  • 7

1 Answers1

4

The problem isn't the returning, but rather the assignment to arr in the main function.

You can't assign to an array, only to its individual elements. You can also copy to an array.

However, in this case there's no need for an assignment (or a copy), since you modify the array in-place. So all you really need is:

square_all(arr);  // No assignment

A larger problem is your use of sizeof in the functions. Because you don't pass an array to the functions, you pass a pointer. And the size of a pointer is the size of a pointer is the size of the actual pointer itself and not what it might point to.

See Why isn't the size of an array parameter the same as within main?

Furthermore, since array indexes are zero-based, an array of X elements will have indexes from 0 to X - 1, inclusive. That means a loop-condition like i <= X will include X as an index, and that's out of bounds. Use i < X as a loop condition instead.

My guess is that you misunderstood how arrays are passed to functions, that arrays are copied for the function calls, which they are not. A function argument declaration like int arr[] is actually translated by the compiler as int *arr. And when you call the function, you only pass a pointer to its first element (e.g. print(arr) is really equal to print(&arr[0])).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621