Dynamic structures

Hi, may be somebody can give me the idea, where can be a problem.
Whenever I output after taking the value from input stream (line 17) it works fine, but if I do output (line 23) after 'for' loop it gives very strange results, in particular second name is replaced with number.

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
#include<iostream>
struct contrib{
	double amt;
	char name[20];
};
int main(){
	using namespace std;
	int n;
	int i;
	contrib *patrons=new contrib[n];
	cout << "Enter number of patrons: ";
	cin >> n;
	for(i=0;i<n;i++){
		cout << "Enter the name of patron " << i+1 << " : ";
		cin.get();
		cin.getline((patrons[i].name),20);
		cout << patrons[i].name << endl;
		cout << "Enter the amount of contribution for patron " << i+1 << " : ";
		cin >> (patrons[i].amt);
		cout << patrons[i].amt << endl;
	}
	cout << (patrons[0].name) << endl;
	cout << (patrons[1].name) << endl;
	cout << (patrons[0].amt) << endl;
	cout << (patrons[1].amt) << endl;
	delete [] patrons;
	return 0;
}


Enter number of patrons: 2
Enter the name of patron 1 : Tom Smith
Tom Smith
Enter the amount of contribution for patron 1 : 3000
3000
Enter the name of patron 2 : Daddy Best
Daddy Best
Enter the amount of contribution for patron 2 : 10000
10000
Tom Smit
10000
3000
10000
I tested and it worked fine,

I did make one change:

I put
contrib *patrons=new contrib[n];
after you get the input of patrons numbers.

It crashes as n is not initiliazed.

I hope this helps
Thank you, this way it works.
Topic archived. No new replies allowed.