Dynamic Struct Array

Hey people, would just like to ask someone if they could take a look at my code and tell me why it produces a runtime error?

I'm trying to create a dynamic array of structures for an array of "People Profiles" with a few bits of info about those people.

Any help is appreciated :)

Thanks,
Ed

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
#include <iostream>
#include <string>

using namespace std;

struct Profile
{
	string name;
	string hospitalOfBirth;
	string city;
	int dayOfBirth;
	int monthOfBirth;
	int yearOfBirth;
};

int profileNum;

Profile* personProfile = new Profile[profileNum];


int main()
{
	cout << "Enter the number of profiles: ";
	cin >> profileNum;

	for(int i = profileNum; i <= profileNum; i++)
	{
		cout << "Enter the name of this person: ";
		getline(cin, personProfile[i].name);
		cin.ignore();
	}

	delete [] personProfile;

	cin.ignore();
	return 0;
}
for(int i = profileNum; i <= profileNum; i++)

Let's say profileNum was entered in as 3.

i = 3; i <= 3; i++. This is a problem. Try i = 0; and i < profileNum.

Profile* personProfile = new Profile[profileNum];

This line is a problem. You need to give this array a size. new Profile[5] for example would be a valid size and you would not get that runtime error. At the moment, the size is whatever junk value is in int profileNum.
Last edited on
Okay, thanks for the help :)

Firstly, if I give

Profile* personProfile = new Profile[profileNum];

a value, is it not then a constant sized array??

Sorry if this is a stupid question, the new operator is quite "new" to me.

Thanks,
Ed

EDIT: Actually don't worry, just changed the program and now it works xD

Thanks a lot!
Last edited on
Topic archived. No new replies allowed.