scdmb
scdmb

Reputation: 15621

Pointers of two dimensional array

There is such code:

int (*ptr_)[1] = new int[1][1];
ptr_[0][0] = 100;
std::cout << "to: " << &ptr_ << ' ' << ptr_ << ' ' << *ptr_ << ' ' << &(*ptr_) << ' ' << **ptr_ << std::endl;

Result is:

to: 0xbfda6db4 0x9ee9028 0x9ee9028 0x9ee9028 100

Why values of ptr_ and *ptr_ are the same? Value of ptr_ equals to 0x9ee9028, so value of memory cell 0x9ee9028 is *ptr_ which is 0x9ee9028, however **ptr_ gives result 100. Is it logical?

Upvotes: 3

Views: 207

Answers (2)

Tom
Tom

Reputation: 2016

int main() {
  int test[2][3] = { {1,2,3}, {4, 5, 6} };
  int (*pnt)[3] = test; //*pnt has type int[3]

  //printArray writes array to stdout
  printArray(3, *pnt); //returns 1 2 3
  printArray(3, *(pnt+1)); //returns 4 5 6
  return 0;
}

mutl-dimentional arrays are really arrays for arrays, for example test[2][3] is an array with two elements that are of type int[3] which in turn have 3 integer elements.

In your case you have a pointer to a pointer to a variable.

In other words your array looks like this:

array = {{100}}
  1. ptr_ points to array
  2. &ptr_ is the address of outer array
  3. ptr_ is the address of first element (which is to another array)
  4. *ptr_ same as above
  5. &(*ptr_) gets first element of outer array which is the innter array, then returns the address of the innter array
  6. **ptr_ gets first element of outer array (which is the inner array) then dereferences the innter array which is an actuall value

Upvotes: 1

Mark B
Mark B

Reputation: 96241

ptr_ is a pointer to an array of length one. Variables of array type in C and C++ simply degrade to pointers when printed (among other things). So when you print ptr_ you get the address of the array. When you print *ptr_ you get the array itself, which then degrades right back into that same pointer again.

But in C++ please use smart pointers and standard containers.

Upvotes: 3

Related Questions