0

Is there any major difference between them? To me it looks the same...and according to some googling it seems the same as well..Just wanna confirm it here..

void getAnything(int arr [])
{
    arr[0] = 2;
}

versus

void getAnything(int *arr)
{
    arr[0] = 2;
}  

main

int main()
{
    int arr [1];
    getAnything(arr);
}
Zhi J Teoh
  • 61
  • 5
  • 2
    This is probably a duplicate. As a parameter declaration (and *only* as a parameter declaration), `int arr []` really means `int *arr`. There are no parameters of array type. An expression of array type is, in most contexts, implicitly converted to a pointer to its first element. Which is why `sizeof arr` inside the function gives you the size of a pointer, not the size of the array; you have to track that yourself. Read section 6 of the [comp.lang.c FAQ](http://www.c-faq.com/); it applies to C++ as well as to C. – Keith Thompson Dec 09 '14 at 20:46
  • Related: http://stackoverflow.com/questions/12127625/array-syntax-vs-pointer-syntax-in-c-function-parameters – R Sahu Dec 09 '14 at 20:51
  • You could have just compiled the code and the compiler would have stated that the functions are the same, thus an error would have been emitted. http://ideone.com/xrtFYW – PaulMcKenzie Dec 09 '14 at 21:01

2 Answers2

1

It is the same. In fact, i you would have something like

void getAnything(int arr [10])
{
    arr[0] = 2;
}

would also be the same.

Bogdan V.
  • 719
  • 4
  • 7
0

Yes, they are precisely equivalent:

[C++11: 8.3.5/5]: [..] After determining the type of each parameter, any parameter of type “array of T” or “function returning T” is adjusted to be “pointer to T” or “pointer to function returning T,” respectively. [..]

It's quite confusing because it means that your argument need not actually have anything to do with arrays whatsoever, but there you go; thanks, C! It also helps to encourage the myth that "arrays are pointers", sadly.

All of the following:

void foo(int[]   x);
void foo(int[5]  x);
void foo(int[42] x);

actually mean this:

void foo(int* x);
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055