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");
}
1 Answer 1
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
3 Comments
* to int * gives intint * p defines p to point to an int. If you apply the de-referencing operator * to p you get what is points to, that is an int here.Explore related questions
See similar questions with these tags.
p[5]here. Clearly, there is no assignment to anyp[i].p = &a[0];should not compile.int *p[5]is the wrong type. Just another author having trouble with arrays and pointers and the syntax in C. A pointer to the inner array would beint (*p)[5]- notice the parenthesis!