Dynamic memory allocation in Table 2D

Hi everyone! I allocate memory in 2D table by the method as you see in my code.
Program compile good. After running of program i write down these:

Write down the number of columns
5
1 1 1
2 3 4
1 2 3
2 4 5

and when I want to write down the last row program stops working.. I dont know why and where is the mistake..?

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
37
38
39
40
41
42
#include<iostream>
#include<cmath>
using namespace std;


void gl1(){
	int k;//amount of columns
	cout << "Write down the number of columns" << endl;
	cin >> k;

	int r = 3;//amount of rows
	//Dynamic memory allocation
	int **T = new int *[r];
	for (int i = 0; i < r; ++i)
		T[i] = new int[k];

	for (int i = 0; i < k; i++)
	{
		int a=0, b=0, c=0;
		cin >> a;
		cin >> b;
		cin >> c;
		T[i][0] = a;
		T[i][1] = b;
		T[i][2] = c;

	}
	for (int i = 0; i < k; i++)	{	
		for (int j = 0; j < r; j++)	{
			cout << T[i][j] << " ";
		}
		cout<<endl;
	}
	

}


int main(){
	gl1();
	return 0;
}
1
2
3
4
	for (int i = 0; i < k; i++)	{	
		for (int j = 0; j < r; j++)	{
			cout << T[i][j] << " ";
		}
You mixed rows/columns here. You have r rows and k columns.
Nope i try run this:

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<cmath>
using namespace std;


void gl1(){
	int k;//amount of columns
	cout << "Write down the number of columns" << endl;
	cin >> k;

	int r = 3;//amount of rows
	//Dynamic memory allocation
	int **T = new int *[r];
	for (int i = 0; i < r; ++i)
		T[i] = new int[k];

	for (int i = 0; i < k; i++)
	{
		int a=0, b=0, c=0;
		cin >> a;
		cin >> b;
		cin >> c;
		T[i][0] = a;
		T[i][1] = b;
		T[i][2] = c;

	}

}


int main(){
	gl1();
	return 0;
}


and the problem is still the same..
Again, you did not fix anything.

You have only three rows.
T[i][0] = a; What do you think happend when i >= 3 ?
Ok now I solve the problem thx very much my code now looks like this:
#include<iostream>
#include<cmath>
using namespace std;


void gl1(){
int r;//amount of columns
cout << "Write down the number of columns" << endl;
cin >> r;

int k=3;//amount of columns
//Dynamic memory allocation
int **T = new int *[r];
for (int i = 0; i < r; ++i)
T[i] = new int[k];

for (int i = 0; i < r; i++)
{
int a=0, b=0, c=0;
cin >> a;
cin >> b;
cin >> c;
T[i][0] = a;
T[i][1] = b;
T[i][2] = c;

}
for (int i = 0; i < r; i++) {
for (int j = 0; j < k; j++) {
cout << T[i][j] << " ";
}
cout<<endl;
}

}


int main(){
gl1();
return 0;
}
Topic archived. No new replies allowed.