Dynamic Array of Structures

This is a problem from C++ Primer Plus that I am stuck on. I googled around and I am still not sure how my syntax is wrong. I'm getting this error on line 19 (indicated below): In function 'int main()': 19:24: error: expected type-specifier before 'carInfo' 19:24: error: cannot convert 'int*' to 'car*' in initialization 19:24: error: expected ',' or ';' before 'carInfo'

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

using namespace std;

struct car
{   
    string make;
    int year;
};
  
int main()
{
    //Prompt user for how many cars to catalogue
    int carNum;
    cout << "How many cars would you like to catalogue?";
    cin >> carNum;
    
    car* carInfo = new carInfo[carNum]; //Error on this line
    
    //For all the cars, populate the year and make
    for (int i = 0; i <= carNum - 1; i++)
    {
        cout << "\nWhat is the make for car #" << i + 1 << "?";
        cin >> carInfo[i].make;
        cout << "\nWhat is the year for car #" << i + 1 << "?";
        cin >> carInfo[i].year;
    }

    return 0; 
}
What is that second "carInfo" between new and [carNum]?
Derp... thanks keskiverto.

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

using namespace std;

struct car
{   
    string make;
    int year;
};
  
int main()
{
    //Prompt user for how many cars to catalogue
    int carNum;
    cout << "How many cars would you like to catalogue?";
    cin >> carNum;
    
    car* carInfo = new car[carNum]; //fixed
    
    //For all the cars, populate the year and make
    for (int i = 0; i <= carNum - 1; i++)
    {
        cout << "\nWhat is the make for car #" << i + 1 << "?";
        cin >> carInfo[i].make;
        cout << "\nWhat is the year for car #" << i + 1 << "?";
        cin >> carInfo[i].year;
    }

    return 0; 
}
Last edited on
Topic archived. No new replies allowed.