Pointer arithmetic on multi-dimensional arrays

Using an example of my book

int array[4][4];

to access array[3][2]

the author says the pointer arithmetic that is being performed is
 
*(array + 3 * <width of array> + 2)


I know *(array + 3) gives you row 3 but I don't understand how multiplying it by the width of the array and adding 2 gives you array[3][2].

I would really appreciate it if someone took the time to explain this to me. I went over the section yesterday and re-read it 2 times and decided to give up on it and come back to it today and I'm still have trouble with it.
Ok, firstly you'll have to understand how exactly elements are stored in a 2 D array.

In a 2D array(of integers, floats, doubles etc) you access the element array[3][2] simply. The reason is that when you declare a 2 D array, the CPU stores them in contiguous(one after the another) memory locations. So, your int array[2][2] would look something like this:

array[0][0]     array[0][1]     array[1][1]     array[1][2]

1001            1005            1009            1013


where 1001,...,1013 are memory locations(I assume that the size of an integer in your machine is 4 bytes).

If you want to access array[0][1], then you just do array[0][1]. But in C++, an array is treated somewhat like a pointer. The array name(in this case array) points to the base address of array(in this case array[0][0]). So, when you do array[0][1], the CPU finds the element concerned as follows:

the address of array[0][1] = ( base address of array + 4 * 0 ) + 1

Similarly, an array of integer pointers are also similarly stored. But if you are familiar with pointer arithmetic, I guess you'll figure out what your book says.

But in case of an array of pointers, you'll have to do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.
.
.
int *int_pointer_array[no_of_rows][no_of_columns];
.
.
for(int r = 0; r < no_of_rows; r++)
{
     for(int c = 0; c < no_of_columns; c++)
     {
            cin >> int_pointer_array[r * no_of_columns + c];
     }
}
.
.
.


If you examine closely, you'll find the similarity between the two. In your case if you plug the values of the indices of your required elements and use the above formula in the code, you'll understand what I mean.

Hope this short lecture helped :)
Last edited on
Yes it helped a lot, thanks!
Topic archived. No new replies allowed.