Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers of two dimensional array

Tags:

c++

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?

like image 668
scdmb Avatar asked Apr 06 '26 02:04

scdmb


1 Answers

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.

like image 159
Mark B Avatar answered Apr 08 '26 14:04

Mark B