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).

3
  • 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. Commented May 13, 2015 at 20:14
  • @RemyLebeau I think in the second example the parameter is adjusted to int (*)[M]. Commented May 13, 2015 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. Commented May 13, 2015 at 20:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.