# Thread: Incorrect pointer conversion when accessing a[2][2] with *b.

1. ## Incorrect pointer conversion when accessing a[2][2] with *b.

Hi

When running following code, it gives correct output but a warning something like: "Incorrect Pointer Conversion"

Code:
```void main()
{
int a[2][2] = {{1,2}, {3,4}}, *b = &a;

printf("*b = %d", *b);
printf("*(b+1) = %d", *(b+1) );
printf("*(b+2) = %d", *(b+2) );
printf("*(b+3) = %d", *(b+3) );
}```

please help me out with this, why is this incorrect? And how is a 2d pointer saved in memory? Isnt it in sequence like this - a[0][0], a[0][1], a[1][0], a[1][1]
If this is correct, above method should work just fine ...

Also please tell me all the methods one can use to access an array 2d, 3d anything, from a function ...

2. Code:
```#include <stdio.h>

int main( void )
{
int a[2][2] = {{1,2}, {3,4}}, *b = &a[0][0];

printf("*b = %d", *b);
printf("*(b+1) = %d", *(b+1) );
printf("*(b+2) = %d", *(b+2) );
printf("*(b+3) = %d", *(b+3) );
return 0;
}```
Kurt

3. > please help me out with this, why is this incorrect?
Because (in your code), the type of &a is a pointer to an array - specifically int (*)[2][2]

Code:
```\$ cat foo.c
#include <stdio.h>
int main()
{
int a[2][2] = {{1,2}, {3,4}};

// points to the whole array
int (*b)[2][2] = &a;

// points to a row of the array
// x and &x[0] have the same type
int (*c1)[2] = a;
int (*c2)[2] = &a[0];

// points to an element of the array
// x and &x[0] have the same type
int *d1 = a[0];
int *d2 = &a[0][0];

// lots of different pointers, with different types,
// all pointing to the same place
printf("%p %p\n%p %p\n%p %p\n",
(void*)a, (void*)b,
(void*)c1, (void*)c2,
(void*)d1, (void*)d2 );
return 0;
}
\$ gcc foo.c
\$ ./a.out
0x7fff9f564fc0 0x7fff9f564fc0
0x7fff9f564fc0 0x7fff9f564fc0
0x7fff9f564fc0 0x7fff9f564fc0```
> And how is a 2d pointer saved in memory? Isnt it in sequence like this - a[0][0], a[0][1], a[1][0], a[1][1]
Yes it is.

But you need to be really careful about your terminology here.
Arrays and Pointers
Arrays and pointers are closely related, but you can't just mix and match using "pointer" and "array" in your descriptions without creating confusion.

4. Also, if you want help understanding more complex types/declarations in C, like what Salem posted, e.g.
Code:
`int (*c1)[2]`
I find this site useful: Reading C type declarations

Popular pages Recent additions