0

I have the following function:

void foo(int arr[])
{
   arr++;        // No error. If I dereference arr and print it, I get 2
}

int main()
{
  int x[3];
  x[0]=1;
  x[1]=2;
  x[2]=3;
  foo(x);       //No error
  x++;          //Error. 
}

Why don't I get an error when I carry out the operation in foo() but I get one when I do it in main? As far as I know, both arr in foo() and x in main() are pointers to the exact same location, the first element in x. So I should've been able to perform both x++ and arr++.

mrsinister
  • 97
  • 2
  • 7
  • 5
    `x` in `main` is not a pointer, it's an array (which decays to a pointer in many uses, but is not the same; you can't assign to `x` directly). `arr` in `foo` is a pointer. – Colonel Thirty Two Oct 21 '15 at 13:15
  • 4
    `void foo(int arr[])`is actually exactly the same as `void foo(int *arr)`. – Jabberwocky Oct 21 '15 at 13:16
  • 2
    To add to the above comment. `x` in `main()` is a non-modifiable L-value. You cannot assign to it or increment it. – Haris Oct 21 '15 at 13:17
  • Gj at finding a duplicate, I failed but came across some other posts that may be of interest: [Is array name a pointer?](http://stackoverflow.com/questions/1641957/is-array-name-a-pointer-in-c), [What is array decaying?](http://stackoverflow.com/questions/1461432/what-is-array-decaying). – Lundin Oct 21 '15 at 13:22

0 Answers0