+ 1

Pointer/Array

int main (){ int a [3][3]= {{1,2,3},{4,5,6},{7,8,9}}; cout << *(*(a+1)); } //////////// Output 4 Questions 1. Adding 1 to the pointer jumps one row but not a column. Why? 2. Why is it needed to use two dereference operator to get the value? https://code.sololearn.com/cUh4UzO21nh7/?ref=app

26th Jul 2019, 4:35 AM
Geral
8 Answers
+ 1
Geral Ok, so I assume your array is supposed to be int a[3][3], and the rest of the code are correct. The explanation is pretty simple, you already know that array is a pointer, so you won't find it hard to understand that two dimensional array is a pointer to a pointer of integer (maybe a bit confusing), like this int** a When you dereference array a one time, it will return you an address to group, so *a will return the address to this group {1, 2, 3}, and *(a + 1) is address of this group {4, 5, 6}. So when you derefence it for the second time, it will return the element in that group, so *(*(a + 1) returns 4 So to simplify all that, two dimensional array is like a simple array that stores elements (numbers), but the elements inside the array are base addresses of other arrays Run the code below, it might help you understand, ask me again if something still unclear https://code.sololearn.com/ciT8zBy1wmQ1/?ref=app
26th Jul 2019, 6:48 AM
Agent_I
Agent_I - avatar
+ 1
It might be related to the issue that making arithmetical operations with pointers depends on the size of data type... char *c; (memory address: 1000) ++c; (new memory address: 1001) short *s; (memory address: 2000) ++s; (new memory address: 2002) Hence, int a [3][3] = {{1,2,3},{4,5,6},{7,8,9}}; **a => 1 *(*(a+1)) => 4; *(*(a+2)) => 7; Does it make sense?
26th Jul 2019, 5:16 AM
Geral
0
Geral Are you sure you declare the array correctly, like int a[3][3] instead of int a[3][3][3] ? Since using two dereference operator in three dimensional array will return an address instead
26th Jul 2019, 6:10 AM
Agent_I
Agent_I - avatar
0
You're right! (That's a typo) P.S. I edited the OP
26th Jul 2019, 6:13 AM
Geral
0
Agent_I Do you know what's going on?
26th Jul 2019, 6:15 AM
Geral
0
If I add it a new line: cout << *(*(a+1)+2); Now, the pointer is on the 2nd row and third column. Why? https://code.sololearn.com/cUh4UzO21nh7/?ref=app
26th Jul 2019, 6:43 AM
Geral
0
Everything is clear now! I was missing the pointer-to-pointer part... Thanks a lot!
26th Jul 2019, 7:01 AM
Geral
0
Try this question after you think you understand 2 dimensional array https://www.sololearn.com/post/130173/?ref=app
30th Jul 2019, 8:57 AM
Cout
Cout - avatar