3

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");
}
alk
71.2k10 gold badges112 silver badges274 bronze badges
asked Mar 20, 2016 at 8:09
9
  • In C a 2D array is just an array of a arrays. Commented Mar 20, 2016 at 8:12
  • You are correct. No need for p[5] here. Clearly, there is no assignment to any p[i]. Commented Mar 20, 2016 at 8:12
  • 1
    p = &a[0]; should not compile. Commented Mar 20, 2016 at 8:12
  • While it might work, it is still wrong and useless. Why not directly index into the 2D array? Anyway, 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 be int (*p)[5] - notice the parenthesis! Commented Mar 20, 2016 at 8:14
  • But when I change it to int*p, it reports (*(p+i))+j) becomes to type int rather than int *. I just want to know what happens here? Commented Mar 20, 2016 at 8:20

1 Answer 1

3
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

answered Mar 20, 2016 at 8:17
Sign up to request clarification or add additional context in comments.

3 Comments

yep, it reports a warning. There should be parenthesis. But most confused me is when I change it to int*p, (*(p+i))+j) becomes to type int rather than int *. Why that happens?
@JenniferQ appying * to int * gives int
@JenniferQ: int * 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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.