Dynamic 2D array - user input

sfuo 0 Tallied Votes 1K Views Share

This program asks for integers from the user and stores them into a multidimensional array that adjusts its size.

#include <iostream>
#include <string>

using namespace std;

void allocate_2D(int **&List, int x, int y, int ycur, int xmax)
{
	//makes a temp for saving data that was in the array
	int **TEMP = List; 
	//creates a new array to the right size
	List = new int*[x];
	for( int i = 0; i < x; i++ )
	{
		List[i] = new int[y];
		for( int j = 0; j < y; j++ )
		{
			List[i][j] = 0;
		}
	}
	//copies info into newly allocated array
	for( int i = 0; i < xmax; i++ )
	{
		for( int j = 0; j <= ycur; j++ )	
		{
			List[i][j] = TEMP[i][j]; 
		}
	}
	//deletes the TEMP array
	for( int i = 0; i < ycur; i++ )
	{
		delete[] TEMP[i];
		TEMP[i] = 0;
	}
	delete[] TEMP;
	TEMP = 0;
}

int main()
{
	string input;
	int xsize = 1, ysize = 1;
	int xcur = 0, ycur = 0, xmax = 0;
	int **List;
	cout << "Enter some integers (input 'r' for new row and 's' for stop):" << endl;
	while(cin >> input)
	{
		if( input == "s" ) //done entering values
			break;
		else if( input == "r" ) //add a row
		{
			ysize++;
			allocate_2D(List, xsize, ysize, ycur, xmax); //makes a new array with another row
			xcur = 0;
			ycur += 1;
		}
		else
		{
			//add a value
			xsize++;
			allocate_2D(List, xsize, ysize, ycur, xmax); //makes a new array with another column
			List[xcur][ycur] = atoi(input.c_str()); //converts input to integer and adds it to the list
			xcur++;
			if( xcur > xmax ) //keeps track of the maxium width of the array
				xmax = xcur;
		}
	}
	//outputs the array
	for( int j = 0; j <= ycur; j++ )
	{
		for( int i = 0; i < xmax; i++ )
		{
			cout << List[i][j] << " ";
		}
		cout << endl;
	}
	system("PAUSE");
	return 0;
}
VernonDozier 2,218 Posting Expert Featured Poster

This snippet sets aside far more memory than is required, mainly due to the fact that both xsize and ysize are continuously incremented without any checks. Used this way, xsize represents the total number of integers typed in (off by one), not the total number of rows. Type in the following:

1 r
2 r
3 r
4 r
[B]s[/B]

and you end up with a 5 x 5 array rather than a 1 x4 array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.