in Programming
615 views
0 votes
0 votes

int B[2][3];
int *p = B; // why this is wrong?
int (*p)[3] = B; // why this is correct?

in Programming
615 views

1 comment

A pointer also has a type and this type is needed for pointer arithmetic. So, a pointer must be declared with the pointed to 'x' data type, where address of an object of type 'x' is assigned to the pointer.
0
0

2 Answers

3 votes
3 votes
When you write B, then it is address of first element of B, Now first element of B is whole 1D array of 3 int, so address of first element can be stored in pointer which points to whole 1D array of 3 int, which is int (*p)[3], not int *p.
0 votes
0 votes

Here Both are correct, depends on what you really need.

#include<stdio.h>
int main(){
    int B[2][3] = {{14,16,18},{19,29,39}};
    int *p = B; // why this is wrong?
    int (*q)[3] = B; // why this is correct?
    printf("%d %d\n",p[0],p[5]);// here p is pointing to single element
    printf("%d \n",q[1][0]);// here q is pointing to whole 1 D array
}

Related questions