-6

So I'm trying to understand pointers in depth and its relation with 2D Array, So I wrote this program. The problem is that the last statement in the code doesn't give me the address of the first 1 D Array as I was expecting. Also, I wanna understand more how all of the other statements worked.

int B[2][3];    
int (*p) [3] = B;

printf("%d\n", &B);
printf("%d\n", &B[0]);
printf("%d\n", &B[0][0]);
printf("%d\n", B);
printf("%d\n", B[0]);
printf("%d\n", *B);
printf("%d\n", *B[0]);

Thank you

NAS
  • 19
  • 5
  • 2
    Arrays aren't pointers and vice versa. – πάντα ῥεῖ Oct 07 '18 at 01:22
  • @πάντα ῥεῖ But the name of the array is a pointer to the first element of the array. This is why printing B or B[0] give the address of the first element of the array. Am i wrong? – NAS Oct 07 '18 at 01:35
  • Slightly, B[0] is a value, not a memory address. &B = &B[0] = &B[0][0] are memory addresses, which means they are pointers. *&B would yield B[0][0], *B[0][0] doesn't make sense because B[0][0] is the value of the first element of the first row, not the address. – Mario Ishac Oct 07 '18 at 01:38
  • @NAS Check [What is array decaying?](https://stackoverflow.com/questions/1461432/what-is-array-decaying) to get a better understanding and adopt a cleaner terminology. – πάντα ῥεῖ Oct 07 '18 at 01:44
  • @TheeNinjaDev I think B[0] would be a value of the first element if B was a 1D array, but in this case, B[0] is the first 1D Array inside the 2D array B which when your print B[0] it gives the address of the first element of the first 1D array inside the 2D array B. – NAS Oct 07 '18 at 01:45
  • why would you expect dereferencing something to give you an address? did you mean `&`? – xaxxon Oct 07 '18 at 01:57

1 Answers1

3

Why a statement like *B[0] doesn't give the address of the first 1D Array?

Because the indirection operator (*) doesn't return the address of the operand. It does the opposite: It returns the pointed value.

So, since the precedence of subscript operator is higher, B[0] is done first. It results in the first subarray. In the expression *B[0], that subarray decays to pointer to first element of the subarray, and you indirect that pointer to get the pointed value. You failed to initialise that value, so the behaviour of accessing it is undefined.

In the case of a pointer or an array, *arr is equivalent to arr[0]. Therefore *B[0] is equivalent to B[0][0].


PS.

%d is not the correct format specifier for pointers. You need to use %p to avoid undefined behaviour. That will use hexadecimal base. If you insist on decimal, you can convert the pointer to std::uintptr_t, and use the PRIuPTR macro for the format specifier.

But the name of the array is a pointer to the first element of the array.

No, it is not. However, in many cases the array will be implicitly converted to the pointer to first element. This conversion is called decaying.

eerorika
  • 232,697
  • 12
  • 197
  • 326