Public Group

#### Archived

This topic is now archived and is closed to further replies.

# 2d dynamic array

This topic is 5925 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

ok i am just trying some exercises from a c++ book. i am to create a 2d array dynamically using a "pointer to a pointer". my task is to construct a 4x4, 2d array of integers using this method. is the "delete" portion at the end correct?

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
int value[4]  = {1,2,3,4};
int value1[4] = {5,6,7,8};
int value2[4] = {9,10,11,12};
int value3[4] = {13,14,15,16};

//inititalize 2d pointer

int** parray;

//pointer to "array of 4 pointers"

parray = new int*[4];

parray[0] = value; //1st pointer in "array of pointers",

//pointing to array of integers

parray[1] = value1;
parray[2] = value2;
parray[3] = value3;

//output

for(int index=0; index<4; index++)
{
cout << *(parray[0] + index);
cout << *(parray[1] + index);
cout << *(parray[2] + index);
cout << *(parray[3] + index);
}

delete [] parray;
parray =0;

return 0;
}


##### Share on other sites
yes, but realize whne you completly allocate the array yourself (ie the rows and columns) you must delete the pointers in the array then the array of the pointers. just remeber for every call to new, there is a call to delete. a call with new [] means delete []

##### Share on other sites
Your method works, but is inelegant. Observe:

  int ** parray;.// allocation and initialization:parray = new int *[4];int k = 0;for( int i = 0; i < 4; ++i ){  parray[i] = new int[4];  for( int j = 0; j < 4; ++j, ++k )    parray[i][j] = k;}.// deallocation:for( int i = 0; i < 4; ++i )  delete [] parray[i];delete [] parray;

Note that the above will not compile without tweaking on MSVC due to that compiler''s broken for-scoping.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ ]
[ MS RTFM [MSDN] | SGI STL Docs | Boost ]
Thanks to Kylotan for the idea!

##### Share on other sites
Or he could do all of this in a class and have the deconstructor do all the work for him each time (although he would still have to code it once). Make sure when creating dynamic memory in a class that the copy constructor is overloaded to take the original array as a reference not as a copy, otherwise you will get into a infinate recursion loop.

If at first you don''t succeed, use profanity and try, try again.

1. 1
Rutin
25
2. 2
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 14
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631757
• Total Posts
3002131
×