{"id":2550,"date":"2015-09-14T15:44:43","date_gmt":"2015-09-14T23:44:43","guid":{"rendered":"https:\/\/fandai.donguapan.workers.dev:443\/http\/www.learncpp.com\/?p=2550"},"modified":"2024-09-09T21:42:25","modified_gmt":"2024-09-10T04:42:25","slug":"pointers-to-pointers","status":"publish","type":"post","link":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/pointers-to-pointers\/","title":{"rendered":"19.4 &#8212; Pointers to pointers and dynamic multidimensional arrays"},"content":{"rendered":"<p>This lesson is optional, for advanced readers who want to learn more about C++.  No future lessons build on this lesson.<\/p>\n<p>A pointer to a pointer is exactly what you\u2019d expect: a pointer that holds the address of another pointer.<\/p>\n<p><strong>Pointers to pointers<\/strong><\/p>\n<p>A normal pointer to an int is declared using a single asterisk:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int* ptr; \/\/ pointer to an int, one asterisk<\/code><\/pre>\n<p>A pointer to a pointer to an int is declared using two asterisks<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int** ptrptr; \/\/ pointer to a pointer to an int, two asterisks<\/code><\/pre>\n<p>A pointer to a pointer works just like a normal pointer \u2014 you can dereference it to retrieve the value pointed to.  And because that value is itself a pointer, you can dereference it again to get to the underlying value.  These dereferences can be done consecutively:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int value { 5 };\r\n\r\nint* ptr { &amp;value };\r\nstd::cout &lt;&lt; *ptr &lt;&lt; '\\n'; \/\/ Dereference pointer to int to get int value\r\n\r\nint** ptrptr { &amp;ptr };\r\nstd::cout &lt;&lt; **ptrptr &lt;&lt; '\\n'; \/\/ dereference to get pointer to int, dereference again to get int value<\/code><\/pre>\n<p>The above program prints:<\/p>\n<pre>\r\n5\r\n5\r\n<\/pre>\n<p>Note that you can not set a pointer to a pointer directly to a value:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int value { 5 };\r\nint** ptrptr { &amp;&amp;value }; \/\/ not valid<\/code><\/pre>\n<p>This is because the address of operator (operator&#038;) requires an lvalue, but &#038;value is an rvalue.<\/p>\n<p>However, a pointer to a pointer can be set to null:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int** ptrptr { nullptr };<\/code><\/pre>\n<p><strong>Arrays of pointers<\/strong><\/p>\n<p>Pointers to pointers have a few uses.  The most common use is to dynamically allocate an array of pointers:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int** array { new int*[10] }; \/\/ allocate an array of 10 int pointers<\/code><\/pre>\n<p>This works just like a standard dynamically allocated array, except the array elements are of type &#8220;pointer to integer&#8221; instead of integer.<\/p>\n<p><strong>Two-dimensional dynamically allocated arrays<\/strong><\/p>\n<p>Another common use for pointers to pointers is to facilitate dynamically allocated multidimensional arrays (see <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/multidimensional-c-style-arrays\/\">17.12 -- Multidimensional C-style Arrays<\/a> for a review of multidimensional arrays).<\/p>\n<p>Unlike a two dimensional fixed array, which can easily be declared like this:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int array[10][5];<\/code><\/pre>\n<p>Dynamically allocating a two-dimensional array is a little more challenging.  You may be tempted to try something like this:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int** array { new int[10][5] }; \/\/ won\u2019t work!<\/code><\/pre>\n<p>But it won&#8217;t work.<\/p>\n<p>There are two possible solutions here.  If the rightmost array dimension is constexpr, you can do this:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int x { 7 }; \/\/ non-constant\r\nint (*array)[5] { new int[x][5] }; \/\/ rightmost dimension must be constexpr<\/code><\/pre>\n<p>The parenthesis are required so that the compiler knows we want <code>array<\/code> to be a pointer to an array of 5 <code>int<\/code> (which in this case is the first row of a 7-row multidimensional array).  Without the parenthesis, the compiler would interpret this as <code>int* array[5]<\/code>, which is an array of 5 <code>int*<\/code>.<\/p>\n<p>This is a good place to use automatic type deduction:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int x { 7 }; \/\/ non-constant\r\nauto array { new int[x][5] }; \/\/ so much simpler!<\/code><\/pre>\n<p>Unfortunately, this relatively simple solution doesn&#8217;t work if the rightmost array dimension isn&#8217;t a compile-time constant.  In that case, we have to get a little more complicated.  First, we allocate an array of pointers (as per above).  Then we iterate through the array of pointers and allocate a dynamic array for each array element.  Our dynamic two-dimensional array is a dynamic one-dimensional array of dynamic one-dimensional arrays!<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int** array { new int*[10] }; \/\/ allocate an array of 10 int pointers \u2014 these are our rows\r\nfor (int count { 0 }; count &lt; 10; ++count)\r\n    array[count] = new int[5]; \/\/ these are our columns<\/code><\/pre>\n<p>We can then access our array like usual:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">array[9][4] = 3; \/\/ This is the same as (array[9])[4] = 3;<\/code><\/pre>\n<p>With this method, because each array column is dynamically allocated independently, it\u2019s possible to make dynamically allocated two dimensional arrays that are not rectangular.  For example, we can make a triangle-shaped array:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int** array { new int*[10] }; \/\/ allocate an array of 10 int pointers \u2014 these are our rows\r\nfor (int count { 0 }; count &lt; 10; ++count)\r\n    array[count] = new int[count+1]; \/\/ these are our columns<\/code><\/pre>\n<p>In the above example, note that array[0] is an array of length 1, array[1] is an array of length 2, etc\u2026<\/p>\n<p>Deallocating a dynamically allocated two-dimensional array using this method requires a loop as well:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">for (int count { 0 }; count &lt; 10; ++count)\r\n    delete[] array[count];\r\ndelete[] array; \/\/ this needs to be done last<\/code><\/pre>\n<p>Note that we delete the array in the opposite order that we created it (elements first, then the array itself).  If we delete array before the array columns, then we\u2019d have to access deallocated memory to delete the array columns.  And that would result in undefined behavior.<\/p>\n<p>Because allocating and deallocating two-dimensional arrays is complex and easy to mess up, it\u2019s often easier to \u201cflatten\u201d a two-dimensional array (of size x by y) into a one-dimensional array of size x * y:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">\/\/ Instead of this:\r\nint** array { new int*[10] }; \/\/ allocate an array of 10 int pointers \u2014 these are our rows\r\nfor (int count { 0 }; count &lt; 10; ++count)\r\n    array[count] = new int[5]; \/\/ these are our columns\r\n\r\n\/\/ Do this\r\nint *array { new int[50] }; \/\/ a 10x5 array flattened into a single array<\/code><\/pre>\n<p>Simple math can then be used to convert a row and column index for a rectangular two-dimensional array into a single index for a one-dimensional array:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int getSingleIndex(int row, int col, int numberOfColumnsInArray)\r\n{\r\n     return (row * numberOfColumnsInArray) + col;\r\n}\r\n\r\n\/\/ set array[9,4] to 3 using our flattened array\r\narray[getSingleIndex(9, 4, 5)] = 3;<\/code><\/pre>\n<p><strong>Passing a pointer by address<\/strong><\/p>\n<p>Much like we can use a pointer parameter to change the actual value of the underlying argument passed in, we can pass a pointer to a pointer to a function and use that pointer to change the value of the pointer it points to (confused yet?).<\/p>\n<p>However, if we want a function to be able to modify what a pointer argument points to, this is generally better done using a reference to a pointer instead.  This is covered in lesson <a href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/pass-by-address-part-2\/\">12.11 -- Pass by address (part 2)<\/a>.<\/p>\n<p><strong>Pointer to a pointer to a pointer to\u2026<\/strong><\/p>\n<p>It\u2019s also possible to declare a pointer to a pointer to a pointer:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int*** ptrx3;<\/code><\/pre>\n<p>This can be used to dynamically allocate a three-dimensional array.  However, doing so would require a loop inside a loop, and is extremely complicated to get correct.<\/p>\n<p>You can even declare a pointer to a pointer to a pointer to a pointer:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int**** ptrx4;<\/code><\/pre>\n<p>Or higher, if you wish.<\/p>\n<p>However, in reality these don\u2019t see much use because it\u2019s not often you need so many levels of indirection.<\/p>\n<p><strong>Conclusion<\/strong><\/p>\n<p>We recommend avoiding using pointers to pointers unless no other options are available, because they\u2019re complicated to use and potentially dangerous.  It\u2019s easy enough to dereference a null or dangling pointer with normal pointers \u2014 it\u2019s doubly easy with a pointer to a pointer since you have to do a double-dereference to get to the underlying value!<\/p>\n<div class=\"prevnext\"><div class=\"prevnext-inline\">\n\t<a class=\"nav-link\" href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/void-pointers\/\">\n <div class=\"nav-button nav-button-next\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Next lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">19.5<\/span>Void pointers\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  \t<a class=\"nav-link\" href=\"\/https\/www.learncpp.com\/\">\n  <div class=\"nav-button nav-button-index\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-home\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Back to table of contents<\/div>\n    <\/div>\n<\/div><\/a>\n  \t<a class=\"nav-link\" href=\"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/destructors\/\">\n  <div class=\"nav-button nav-button-prev\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-left\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Previous lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">19.3<\/span>Destructors\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  <\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>This lesson is optional, for advanced readers who want to learn more about C++. No future lessons build on this lesson. A pointer to a pointer is exactly what you\u2019d expect: a pointer that holds the address of another pointer. Pointers to pointers A normal pointer to an int is &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/2550"}],"collection":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/comments?post=2550"}],"version-history":[{"count":39,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/2550\/revisions"}],"predecessor-version":[{"id":17589,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/2550\/revisions\/17589"}],"wp:attachment":[{"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/media?parent=2550"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/categories?post=2550"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/tags?post=2550"}],"curies":[{"name":"wp","href":"https:\/\/fandai.donguapan.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}