Question:
Pointers to pointers in C++?
?
2014-06-25 07:10:12 UTC
I am currently reading a book on C++ and am slightly confused by the topic of pointers to pointers. I have a few questions:

1. To define a pointer to a pointer, you do the following:
int* p1;
int** pp2;
int pp2 = &p1;
Why is pp2 assigned to &p1? I understand that the point is to assign pp2 to the address of p1, but since p1 is a pointer, doesn't that mean that pp2 should be assigned to plain old p1 (since a pointer's address can be used without the need of the address of (&) operator).

2. When assigning a pointer to an array you do the following
int x[12];
int *q = x;
In the book I am reading, it mentions that to assign a pointer to a multidimensional array you do (not) do the following
int x[8][12];
int** q = x;
The book then mentions that this does not work (which it does not), but why would one even consider having a pointer point to an array, but have a pointer to a pointer point to a multidimensional array? I tried, after reading this, having a single pointer point to the multidimensional array, but that did not work either. Why not? The book does provide a brief explanation to why, but it is not as in depth as I would like it to be.


Thank you in advance.
Three answers:
husoski
2014-06-25 07:53:45 UTC
1 The type of p1 is not just a pointer...it's a pointer to an int. That's important. You can't mix pointers to different types (with an exception involving assigning a void* pointer). Since p1 points to an int, and pp1 is expected to point to a pointer (to an int), they are incompatible and pp1 = p1; is disallowed.



&p1 returns a pointer to p1, which is the pointer to a pointer to an int that pp1 needs.



2. The pointer-array duality in C/C++ is stressed so much that people start thinking that arrays are pointers. They are not.



An array name is (almost always) converted to a pointer to the first element of that array when used in an expression. If x is an array, the the name x in an expression is treated as &x[0].



For int x[12], x[0] is an int and x is treated to a pointer to an int.



For int x[8][12], x[0] is an array (NOT a pointer), so x is treated as a pointer to an array of ints. That's not the same as a pointer to a pointer.
?
2014-06-25 13:51:27 UTC
You can assign a pointer to a multi-dimensional array. It essentially treats the array as a sequential list of data. You can access the elements using pointer arithmetic.
?
2014-06-25 08:45:40 UTC
Thank you for clearing this up. I greatly appreciate it


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...