I'm trying to understand pointer arithmetic in 2D vector.
I thought that if I have 2D vector at the size: M[3][3]
and *ptr=&M[0][0]
than ptr[4]
is equal to M[1][2]
, but it seems to be wrong.
Can you please help me out with this?
2D arrays are arranged in Row-major order , so the 3 columns of row 0 come first, followed by the 3 columns of row 1, etc. Your concept is correct, but your counting is off: it's M[1][1].
Note that you might run into problems due to pointer aliasing depending on your code and how agressively your compiler tries to optimize.
M[3][3] is laid out in memory as [0,0] [0,1] [0,2] [1,0] [1,1] [1,2] [2,0] [2,1] [2,2]
so ptr+4 would be the fourth element of the array [1,1] but since you defined it as a 2d array you can't use a 1d index as shorthand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.