cpointersstatic-allocation

Incrementing pointer to static allocated array


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


Solution

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