carrayspointers

Using pointers with Array in C


What would be the output of the following program?

int main(void) {
    int n[3][3] = {
        2, 4, 3,
        6, 8, 5,
        3, 5, 1
    };
    int i, *ptr;
    ptr = n;
    for (i = 0; i <= 8; i++)
        printf("\n%d", *(ptr + i));
}

Here what does n means w.r.t to two dimensional array? And what ptr will have? I am having lot of confusion using pointers with Array.

Output is coming as 4 everytime. I am trying to understand why it is printing 4 everytime?

Any explanation will help me a lot.


Solution

  • ptr is a pointer that "points" to the first element of the 'n' matrix. You make it doing:

    ptr = n[0];
    

    You can't do:

    ptr = n;
    

    because 'n' is an "array" of "arrays" (the first array store 2, 4 and 3, the second 6, 8 and 5, and so on...)

    When you declare the 'n' two-dimensional array, the elements are stored in memory in linear order (one integer allocation after another) and thats the reason why you can make 'n' point to one element (the first element in this case) and then make it point to the next element (by adding 1 to the pointer, this is called "pointer arithmetic").

    This is the little correction to make the program works in the right way:

    #include <stdio.h>
    
    int main(void) {
        int n[3][3] = {
            2, 4, 3,
            6, 8, 5,
            3, 5, 1
        };
        int i, *ptr;
        ptr = n[0];
        for (i = 0; i <= 8; i++)
            printf("\n%d", *(ptr + i));
    }
    

    The output wil be:

    2 4 3 6 8 5 3 5