2d dynamic array

Started by
2 comments, last by edwinnie 21 years, 11 months ago
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;
}
  
Advertisement
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 []
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 ]
[ Google! | Asking Smart Questions | Jargon File ]
Thanks to Kylotan for the idea!
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.
If at first you don't succeed, use profanity and try, try again.

This topic is closed to new replies.

Advertisement