1

By how much is pointer incremented in these situations and why?

void f(int a[])
{
    a++;
    printf("%d", *a);
}

void g(int a[][M])
{
    a++;
    printf("%d", *a[0]);
}

Lets say that in main I have a static allocated array with n elements and static allocated matrix (2D array) with n rows and M columns and I'm calling functions f and g (I couldn't write this in code because I was unable to post the question with a lot of code and almost no text).

Deanie
  • 2,316
  • 2
  • 19
  • 35
Stefan Golubović
  • 1,225
  • 1
  • 16
  • 21
  • 2
    A pointer is a pointer is a pointer. When you increment a pointer using pointer arithmetic, it increments by an even amount of the byte size of the data type that it is pointing at. You cannot increment an array, but `int a[]` decays to `int *a`, so `a` increments in `sizeof(int)` steps. `int a[][]` decays into `int **a`, so `a` increments in `sizeof(int*)` steps. – Remy Lebeau May 13 '15 at 20:14
  • @RemyLebeau I think in the second example the parameter is *adjusted to* `int (*)[M]`. – juanchopanza May 13 '15 at 20:31
  • @RemyLebeau There is no array-to-pointer *decay* going on here. **Array parameters** are silently *rewritten* by the compiler to **pointer parameters**. There is absolutely no difference between `void f(int a[])` and `void f(int * a)`. The signatures are completely equivalent. – fredoverflow May 13 '15 at 20:58

1 Answers1

3

In the both cases the pointers are incremented only once.:)

a++;

Their values are changed by the sizeof of the types of objects they point to. So the value of the first pointer is changed by sizeof( int ) and the value of the second pointer is changed by sizeof( int[M] ) Take into account that parameter int a[][M] is adjusted to int ( *a )[M]

Thus within the functions the both pointers will point to second elements of the arrays. For the two-dimensional array its element is one-dimensional array. And this statement

printf("%d", *a[0]);

will output the first element (integer) of the second "row" of the two-dimensional array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335