3

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?

4
  • I'm curious what the exact answer is going to be, but I'm pretty sure it will have something to do with arrays essentially being pointers. Commented Sep 30, 2011 at 15:47
  • 2
    @Pat: you mean, variables of array type essentially being pointers. </pedantic> Commented Sep 30, 2011 at 15:50
  • @larsmas: Hence my non-answer, heh. :P Commented Sep 30, 2011 at 15:53
  • I realise I'm late to this party, but please don't write things like that Pat. I know you realise the subtleties of it, but as it stands your comment is just dangerous. Commented Sep 30, 2011 at 15:54

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Arrays do not degrade to pointers. Variables of array type decay to variables of pointer type. The array remains unharmed.
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.