Search code examples
carrayspointersvariable-declarationpointer-to-array

Array pointer in C program


Here is a C program in textbook, it asks a 3*5 2D array from users and prints the third line.

I am confused with int* p[5]. Why here needs to have [5], I think just int* p is OK. It can repeatedly add and point to the next memory space in the int array. And can anyone explain how pointer works in this program?

#include <stdio.h>

int main(void){
        int a[3][5];
        int i,j;
        int *p[5];

        p = &a[0];
        printf("Please input:\n");
        for(i = 0; i < 3; i++){
                for(j = 0; j<5;j++){
                        scanf("%d\n",(*(p+i))+j);
                }
        }
        p = &a[2];
        printf("the third line is:\n");
        for(j = 0; j<5; j++){
                printf("%5d", *((*p)+j));
        }
        printf("\n");
}

Solution

  • int *p[5];
    

    is an array of five pointers to int.

    What you want is a pointer to an array of five ints

    int (*p)[5];
    

    because &a[0] is the address of the 1st element of a which is an int[5].

    The compiler should have clearly issued at least a warning on this, if not an error, which would be expected.

    More on this here: C pointer to array/array of pointers disambiguation