user3352341
user3352341

Reputation: 33

Pointers of arrays

#include<iostream>
#include<iomanip>

void main()
{      
  int i,j;
  int pole[3][3]={1,2,3,4,5,6,7,8,9};
  *(*(pole+2)+2)=0;

  for(i=0; i<3;i++)
  {
        for(j=0;j<3;j++)
        {
               cout << setw(5)<< pole[i][j];
        }
        cout << endl;
  }
}

This is my program and the output I get is the following:

1 2 3

4 5 6

7 8 0

However, I have troubles understanding what exactly does this line mean:

  *(*(pole+2)+2)=0;

In my understanding, it's a pointer to pointer of array, so basically, the first we do:

*(pole+2)

which points to the 2nd element of the array. Then

*(*(pole+2)+2)

which points to the 4th element of the array? Is this correct? If so, how do we change the last [3][3] element to 0?

Thank you.

Upvotes: 3

Views: 118

Answers (2)

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

Here pole is a 2D array of 3 rows and 3 columns. So as array index starts from 0, you are assigning pole[2][2] = 0 which actually means 0 is assigned to 3rd row and 3rd column element.

*(*(pole+2)+2) == *(pole[2] + 2) == pole[2][2]

Upvotes: 9

Nate
Nate

Reputation: 11

I just learned about pointers in and arrays in depth in my C++ so i hope i can help

you declared a 2D Array which is really just an array of an array of int types.

(pole + 2) points to pole's base address and adds 2(size of an array of ints) to it so:

2*int(4 bytes) * 3(size of array) = 24 bytes

so it adds 24 bytes to the address. it is now pointing to the 3rd array. then it takes that and points to:

3rd arrays base address + 2*int(4bytes)

which will lead it to the 3rd index of that array which is 9. It then changes this value to 0.

the key is that the first pointer is pointing to an Array of arrays. the second pointer points to the index inside of that array.

I hope i didn't confuse you.

Upvotes: 1

Related Questions