1

I know that arrays are similar to pointers in C. Is it safe to say that this means that when I pass an array, say int array[3] = {1, 2, 3}, to another method that changing the values of the passed-in array to int array[3] = {3, 2, 1} change the original array as well? If so, does that mean I essentially don't have to return arrays I pass in due to the fact that any value changes I make to the passed-in array changes the original array's values? (as I understand it, it is in fact impossible to have a function return arrays directly.)

user3735278
  • 261
  • 3
  • 12

2 Answers2

3

You cannot pass an array to a function that way. When you write this:

void myFunc(int ar[]) {
    // ar *looks like* an array?
}

int main() {
    int array[3] = {1,2,3};
    myFunc(array);
}

the compiler will translate it to this:

void myFunc(int *ar) {
    // nope, it's actually a pointer...
}

int main() {
    int array[3] = {1,2,3};
    myFunc(&array[0]); // ... to the first element
}

I recommend not using the void myFunc(int ar[]) syntax, since it only causes confusion. (Writing array instead of &array[0] is acceptable, but only because it's shorter.)

As for your question: since you're actually passing a pointer to the array, then yes, modifying the array the pointer points to will modify the original array (because they're the same array).

user253751
  • 50,383
  • 6
  • 45
  • 81
0
int array[3] = {1,2,3};
myFunc(array);// you are actually passing the base address of the array to myFunc.

your function declaration of myFunc()

void myFunc(int arr[])
{
}

But it is always good to pass the size of the array to the function along with the base address of array,this will help in avoiding array bound errors.

GingerJack
  • 2,898
  • 1
  • 16
  • 17
  • Reading n.m. question that he commented made me arrive at a follow-up question: Can I use sizeof on the array when it's passed to myFunc? – user3735278 Feb 18 '15 at 06:45
  • @user3735278 C is confusing in this sense, but a function parameter `int arr[]` is *adjusted* to `int *arr`. So all you have in such a function is a pointer. All array size information is lost. – juanchopanza Feb 18 '15 at 06:48
  • It is a bit tricky, as the passed array still can be changed using array syntax and, as I know now, changing the array in another function changes the original as well. I was just trying to wrap my head around a problem I was having today, and I just realized that it was simpler than I made it out to be - this answer confirmed that. – user3735278 Feb 18 '15 at 06:51
  • @user3735278 Also note that if your function parameter is *pointer to array*, `void foo(const int (*arr)[10])`, then `sizeof(*arr)` gives the size of the array. But in that case you know its length anyway so there isn't much gain. And C compilers will mostly let you make the mistake of passing an array of the wrong size. – juanchopanza Feb 18 '15 at 06:56