Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

implementation of a dynamic 2D array

Status
Not open for further replies.

rummy98

Programmer
Oct 19, 2001
3
US
I attempted to do this using a pointer to a specific data
type, say int:

int* x;

then i created a single dimension array to hold the columns

x = new * int [10] // this gives me an error for the *
I wouldn't know any other way to create an array of
pointers?!?

then I would use a for loop to traverse the rows:

for (int i = 0; i < 10; i++)
{
x[10] = new int [10];
}

to me, this should create a 10x10 2D array...please find
my error in thinking, this is really frustrating ;)

thanks
rummy
 
You used bad pointer. Istead of using pointer to pointer to int, you used just pointer to int... Check example:

Code:
#include <iostream>

int main()
{
	// you need a pointer to array of (10) pointers :)
	int** array = new int* [10];

	// you need then to allocate memory for (10) arrays
	for ( int i=0; i<10; ++i )
		array[i] = new int[10];

	// do something 
	for ( i=0; i<10; ++i )
	{
		for ( int j=0; j<10; ++j )
		{
			// random value <0,9)
			array[i][j] = ( int ) ( ( rand() / double( RAND_MAX ) ) * 10 );

			// display
			std::cout.width( 3 );
			std::cout << array[i][j] << &quot; &quot;;
		}
		std::cout << std::endl;
	}

	// deallocate (10) arrays
	for ( int j=0; j<10; ++j )
		delete[] array[j];

	// deallocate pointer to (10) arrays
	delete[] array;

	return 0;
}
 
thanks hcexi, I actually didn't know I could

assign a variable as a pointer pointer (**) ;-P

Also, thanks for the destructor...I prolly

would not have destroyed each individual array

before destroying the initial one....there would

have been hanging pointers everywhere. tks again!

rummy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top