two-dimensional dynamic char array

Hi,

I'm trying to create a 2d dynamic array that asks the user to enter however many words they want, then display these in reverse order, like such:


How many words will you enter? 3
Enter word #1: dog
Enter word #2: bites
Enter word #3: cat

cat
bites
dog


This is what I've gotten so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

char **String = 0;

int main()
{	
	int row, column;
	cout << "How many words will you enter? ";
	cin >> row;	
	

	String = new char *[row];
	int i, j;
	for (i=0; i < row; i++)
		String[i] = new char [column];
	
		
	for (i = 0; i < row; i++)
	{
		cout << "Enter word " << i+1 << ": ";
		for (j = 0; j < 25 ; j++)
			cin >> String[i][j]; 
	}



	cout << "Reverse: ";
	for (i = row-1; i > -1; i--)
	{	
		cout << String[i] << endl;
	}
}


my biggest issue right now is that the individual words that I'm inputting aren't correctly being dynamically assigned - each word has to be at least 25 characters before I can get "enter word #2" to show up. Any tips on what I'm doing wrong?
closed account (D80DSL3A)
I found a few problems with your code. See comments in my code below. I tested this and it is working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>// only header required here
using namespace std;

int main()
{
	int row, column = 25;// column was not initialized
	cout << "How many words will you enter? ";
	cin >> row;	

	char **String = 0;// no need to be global variable
	String = new char *[row];
	int i;
	for (i=0; i < row; i++)
		String[i] = new char [column];// 25 characters per word. Do not exceed 24 + one for null terminator)
	
		
	for (i = 0; i < row; i++)
	{
		cout << "Enter word " << i+1 << ": ";		
			cin >> String[i];// no need to cin 1 character at a time
	}

	cout << "Reverse: " << endl;
	for (i = row-1; i > -1; i--)
	{	
		cout << String[i] << endl;
	}

	// release dynamically allocated memory
	for (i=0; i < row; i++)
		delete [] String[i];// each array of characters

	delete [] String;// the array of pointers
	
	return 0;// return type is integer
}
is there any particular reason you can't use std::string and make your life easier?
Topic archived. No new replies allowed.