This is just the beginning of my name sort prog... I am starting with just reading in the names and then outputting each name... As of right now, it is crashing after displaying the first name... I think it's something with my array.. rectangular, instead of square, but don't know what to change...???

#include <iostream>

using namespace std;

char **Create2DArray (unsigned int NumRows, unsigned int NumCols)
{
	char **	TwoDArray;
	TwoDArray = new char * [NumRows];
	for (unsigned int i = 0; i < NumRows; i++)
		TwoDArray [i] = new char [NumRows];	//creates an array for 
       return TwoDArray;
}

void Free2DArray (char **TwoDArray, unsigned int NumCols)
{
	for (int i = 0; i < NumCols; i++)
		delete [] TwoDArray [i];	
	delete [] TwoDArray;		
}

int main ()
{
    unsigned int NumofNames;
    cout << "How many names do you wish to enter? " << endl;
    cin >> NumofNames;

    unsigned int NumCols = 20;
    char ** TwoDArray = Create2DArray (NumofNames, NumCols);
    for (unsigned int i = 0; i < NumofNames; i++)
    {
	cout << "\nEnter a name: ";
	cin >> TwoDArray [i];
    }
	cout << "You have entered: " << *TwoDArray << endl;
	
    Free2DArray(TwoDArray, NumCols);
}

This is just the beginning of my name sort prog... I am starting with just reading in the names and then outputting each name... As of right now, it is crashing after displaying the first name... I think it's something with my array.. rectangular, instead of square, but don't know what to change...???

My comments are inline

#include <iostream>

using namespace std;

char **Create2DArray (unsigned int NumRows, unsigned int NumCols)
{
	char **	TwoDArray;
	TwoDArray = new char * [NumRows];
	for (unsigned int i = 0; i < NumRows; i++)
		TwoDArray [i] = new char [NumCols];	
                    //                       ^^^^^
        return TwoDArray;
}
//You are correct in allocating the 2D array by rows here.  
//Each of your rows should have [U]NumCols[/U] as a length

//FreeArray should take NumRows otherwise you're trying to delete
//20 things when you may have far less
void Free2DArray (char **TwoDArray, unsigned int NumRows)
                                              //   ^^^^^^
{
	for (int i = 0; i < NumRows; i++) //should probably be unsigned
	            //         ^^^^^
                  delete [] TwoDArray [i];	
	delete [] TwoDArray;		
}

//... down in main()
	
     cout << "You have entered: " << *TwoDArray << endl;
//This is not correct.  Make a loop and cout them by TwoDArray[i].

Also, you should look into using cin.getline() instead of the >> operator that way you can have names with spaces.

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.