Adding object to dynamic array using address returned from getArray();

I use a for loop to assign the proper values to the object so the object is completely ready to be added to the dynamic array (using a dynamic array of objects is required)

My brain just cant really figure out how I use the address that is returned from the
getCarArray();
function

How would I add the tempCar object to the dynamic array?
My first thought was to increase the numberOfCars by the newCarQuantity. But that again is a function that returns a given value.

functions.h

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
 //
// Created by agmar on 5/10/2020.
//

#ifndef PA3_FUNCTIONS_H
#define PA3_FUNCTIONS_H

#include "Dealer.h"
#include <string>
#include <iostream>
#include <fstream>

void readData(std::vector<Dealer> &vec)
{
    std::fstream infile("in.txt");
    std::string dealerName;
    int dealerNumber;
    int numberOfCars;

    Car *carArrayPtr;
    std::string VIN;
    std::string MAKE;
    std::string MODEL;
    int YEAR;
    double price;
    std::string test;

    Car dataCar;
    Dealer dataDealer;

   while (infile.good())
    {

        getline(infile, dealerName);
        infile >> dealerNumber;
        infile >> numberOfCars;
        infile.ignore(2);
        dataDealer.setDealerName(dealerName);
        dataDealer.setDealerNumber(dealerNumber);
        dataDealer.setNumberOfCars(numberOfCars);

        //SETTING CARS
        carArrayPtr = new Car[numberOfCars];
        dataDealer.setCarArray(carArrayPtr);


        for (int i = 0; i < numberOfCars; ++i)
        {

            getline(infile, VIN);
            getline(infile, MAKE);
            getline(infile, MODEL);
            infile >> YEAR;
            infile >> price;
            infile.ignore(2);
            dataCar.setVIN(VIN);
            dataCar.setMake(MAKE);
            dataCar.setModel(MODEL);
            dataCar.setYear(YEAR);
            dataCar.setPrice(price);

            carArrayPtr[i] = dataCar;

        }
        vec.push_back(dataDealer);
    }
}
void displayDealers(std::vector<Dealer> &vec)
{
    for (auto & i : vec) {
        std::cout<<i;
    }
//iterate through the dealer vector and not the cars?
}
void displayCars(std::vector<Dealer> &vec)
{
    displayDealers(vec);
    int dealerChoice;
    std::cout<<"Which Dealer would you like to display from?"<<std::endl;
    std::cin>>dealerChoice;
    for(int j=0; j<vec.size(); j++){

        if(vec[j].getDealerNumber() == dealerChoice){

            for(int i=0; i<vec[j].getNumberOfCars(); i++){
                std::cout << vec[j].getCarArray()[i] <<std::endl;
            }
            break;
        }
    }

}
void addCar(std::vector<Dealer> &vec)
{
    Dealer tempDealer;
    Car tempCar;
    Car *cars = tempDealer.getCarArray();

    int newCar;
    std::string newVIN;
    std::string newMake;
    std::string newModel;
    int newYear;
    double newPrice;

    std::cout<<"Which dealer would you like to add the car to? "<<std::endl;
    displayDealers(vec);
    std::cin>>newCar;
    //tempDealer.setDealerName()
    int newCarQuantity;
    std::cout<<"How many cars do you want to add?"<<std::endl;
    std::cin>>newCarQuantity;
    for (int i = 0; i < newCarQuantity; ++i)
    {
        std::cout<<"What are the specs of the this car?"<<std::endl;

        std::cin.ignore();

        std::cout<<"Enter new VIN:";
        getline(std::cin, newVIN);

        std::cout<<"Enter new Make:";
        getline(std::cin, newMake);


        std::cout<<"Enter new Model:";
        getline(std::cin, newModel);


        std::cout<<"Enter new Year:";
        std::cin>>newYear;


        std::cout<<"Enter new Price:";
        std::cin>>newPrice;

        std::cin.ignore();

        tempCar.setVIN(newVIN);
        tempCar.setMake(newMake);
        tempCar.setModel(newModel);
        tempCar.setYear(newYear);
        tempCar.setPrice(newPrice);

        if(vec[i].getDealerNumber() == newCar){
            for(int j=0; j<newCarQuantity; j++){
                tempDealer.setNumberOfCars(tempDealer.getNumberOfCars() + 
newCarQuantity);
                 tempCar = cars[i];
            }
        }


    }




}
void writeDealers(std::vector<Dealer> &vec)
{
//outfile the vector?
}
#endif //PA3_FUNCTIONS_H


Dealer.cpp

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// Created by agmar on 5/10/2020.
//

#include "Dealer.h"
#include <iostream>
#include <fstream>
#include <string>

Dealer::Dealer()
{
    dealerName = "Default";
    dealerNumber = 0;
    numberOfCars = 0;
    carArrayPtr = nullptr;
}
Dealer::Dealer ( std::string _dealerName, int _dealerNumber,int _numberOfCars)
{
dealerName = _dealerName;
dealerNumber = _dealerNumber;
numberOfCars = _numberOfCars;
}

void Dealer::setCarArray(Car *_carArrayPtr) {
    carArrayPtr= _carArrayPtr;
}

void Dealer::setDealerName(std::string _dealerName) {
    dealerName = _dealerName;
    //return dealerName;
}

void  Dealer::setDealerNumber(int _dealerNumber) {
    dealerNumber = _dealerNumber;
    //return dealerNumber;
}
void Dealer::setNumberOfCars(int _numberOfCars) {
    numberOfCars = _numberOfCars;
    //return numberOfCars;
}

std::ostream& operator<<(std::ostream &out, const Dealer &_dealer) {
    out << _dealer.dealerName << "\n" << _dealer.dealerNumber << "\n" << _dealer.numberOfCars<<std::endl;
    return out;
}


//CAR FUNCTIONS

Car::Car()
{
VIN = "DEFAULT";
MAKE = "DEFAULT";
MODEL = "DEFAULT";
YEAR = 0;
price = 0.0;
}
Car::Car(std::string _VIN, std::string _MAKE, std::string _MODEL, int year, double price)
{
    VIN = _VIN;
    MAKE = _MAKE;
    MODEL = _MODEL;
    YEAR = year;
    price = price;
}

void Car::setVIN(std::string _VIN)
{VIN = _VIN;}
void Car::setMake(std::string _MAKE)
{MAKE = _MAKE;}
void Car::setModel(std::string _MODEL)
{MODEL = _MODEL; }
void Car::setYear(int _year)
{YEAR = _year; }
void Car::setPrice(double _price)
{price = _price;}

 std::ostream& operator << (std::ostream & out, Car _car)
 {
     out << _car.VIN << "\n"<< _car.MAKE << "\n"<< _car.MODEL<<"\n"<< _car.YEAR <<"\n" << _car.price << std::endl;
     return out;
 }


Dealer.h
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#ifndef PA3_DEALER_H
#define PA3_DEALER_H

#include <iostream>
#include <fstream>

class Car {
private:
    std::string VIN;
    std::string MAKE;
    std::string MODEL;
    int YEAR;
    double price;
public:
    Car();
    Car(std::string _VIN, std::string _MAKE, std::string _MODEL, int year, double price);
    std::string getVIN(){return VIN;}
    std::string getMake(){return MAKE;}
    std::string getModel(){return MODEL;}
    int getYear() const{return YEAR;}
    double getPrice() const{return price;}
    void setVIN(std::string _VIN);
    void setMake(std::string _MAKE);
    void setModel(std::string _MODEL);
    void setYear(int _year);
    void setPrice(double _price);
    friend std::ostream& operator << (std::ostream & out, Car _car);

};

class Dealer {

private:
    std::string dealerName;
    int dealerNumber;
    int numberOfCars;
    Car *carArrayPtr;

public:

    Dealer();
    Dealer( std::string _dealerName, int _dealerNumber,int _numberOfCars);
    Car* getCarArray(){return carArrayPtr;}
    void setDealerName (std::string _dealerName);
    void setDealerNumber (int _dealerNumber);
    void setNumberOfCars ( int _numberOfCars);
    void setCarArray(Car *_carArrayPtr);
    std::string getDealerName(){return dealerName;}
    int getDealerNumber() const{return dealerNumber;}
    int getNumberOfCars() const{return numberOfCars;}

    friend std::ostream& operator<<(std::ostream& out, const Dealer& _dealer);

};

#endif //PA3_DEALER_H



main.cpp

https://pastebin.com/GYzvnYWX

I haven't learned the whole template class thing yet so I would prefer to not use that method.

Edit: posted full code and added main pastebin (character limit)
Last edited on
basically:
car* tmp = variable.getCarArray();
tmp[index] = value;

you can avoid tmp but the syntax is a little eyebrow raising.
variable.getCarArray()[index] = value; //I think. you may need () or something but along these lines.

You need to know if index is valid... so you probably need something like
int maxindex = getCarArraySize();
.. get index from somewhere???
if(index < maxindex)
as above
else
error text and handling
Last edited on
That was one of the solutions I attempted. It makes complete sense but for some reason the "tmp" pointer cant reach the memory of the array to store it? When I debug it, it runs fine up to that point where it needs to get to the Car class and it ends because it cant. Maybe something is wrong with my actual function itself?
where is the new statement for carArrayPtr?
I believe what you're referring to is this line

 
Car* cars = tempDealer.getCarArray();
Hello nixUe,

Now is the time to show the function that creates the array and maybe share enough code to compile and test the program. Do not make people guess at what might be wrong and get answers that might help.

In the add function you have:
1
2
3
4
5
6
7
8
9
10
Car tempCar(newVIN, newMake, newModel, newYear, newPrice);

//tempCar.setVIN(newVIN);
//tempCar.setMake(newMake);
//tempCar.setModel(newModel);
//tempCar.setYear(newYear);
//tempCar.setPrice(newPrice);
//tempDealer.getNumberOfCars() + newCarQuantity;

cars[i] = tempCar;

First you could make use of the overloaded ctor in place of all the set functions.

When you get to the last line what is the value of "cars"? Does ot point to an array or is it set to "nullptr", "NULL" or some garbage value? You need to answer this before you can start to understand what is wrong.

You will also need to answer the question what variable is used to create the array and does it get a value before you create the array?

Andy

Edit: spelling.
Last edited on
Hello nixUe,

you wrote:

I believe what you're referring to is this line

Car* cars = tempDealer.getCarArray();


No. And that is answering the question. The function should be returning an address that "cars" is being set to. But what is putting the address in the variable Car *carArrayPtr in the first place?

Andy

Edit:
Last edited on
Yes! The "cars" value is set to NULL when I debug

I have edited my original post with my full code,


But what is putting the address in the variable Car *carArrayPtr in the first place?

I think that would be found in the functions.h, these lines.
1
2
carArrayPtr = new Car[numberOfCars];
dataDealer.setCarArray(carArrayPtr);
Dealer tempDealer;
Car tempCar;
Car *cars = tempDealer.getCarArray();

^^^^ cars is invalid there, unless Dealer class constructor allocates memory, which it doesna. It do set it to nullptr, which is what you are seeing.

I would personally give dealer an allocate method and have it call delete in its destructor.
Are you studying pointers? There isn't any need for all this pointer mess, unless you are being forced to do that to learn it -- a <vector> fixes all that sort of stuff and you are using vectors in other places. Can cararray just be a vec??
Last edited on
so the = tempDealer.getCarArray();
is the mistake and is the wrong thing to assign the Car class pointer to?

Is the pointer to the Car class the right way to do this? or am I just making it more difficult for myself.
the mistake is that you have no memory for that pointer; its null by construction.

you need to find a way to allocate memory to that (a new statement) if you want to use it.
Currently, you just construct it, which assigns it to null, then lift it into 'cars' and whatever follows.

not sure what you want to accomplish in that function.
you use cars[i] which is still null as far as I see down on line 150.
and you never seem to touch the vector of dealers, which is passed in.

the one above that reads from a file looks better.... it gets memory and adds to the back of the vector etc.
Last edited on
That makes sense why its assigned to null.
1
2
3
4
    Dealer tempDealer; //assigned to NULL
    Car tempCar; //  default variables
    Car *cars = tempDealer.getCarArray(); // this getCarArray is NULL so the pointer is 
pointing to nothing?

is that correct?

so I need to find a way to have that pointer actually point to the correct memory?
or to this point
find a way to allocate memory to that (a new statement) if you want to use it.

assign a new piece of memory to that pointer?
and then place the new address of memory to the array?
edit: formatting error
Last edited on
yes, that is correct.

and yes, it needs to point to correct memeory, which may be creation of new memory...
so the order of things would look like

Dealer tempDealer; //assigned to NULL
Car tempCar; // default variables
tempDealer.allocatecars(1000); //or whatever. assuming allocatecars is {cararray = new car[])
Car *cars = tempDealer.getCarArray(); // this is valid now, due to above ^^
....
and now main ends an destructor that you wrote (delete[] cararray)
is invoked to release the memory created in the new function.
note that delete[] of a null pointer does no harm.

you can condense it and have the constructor (a second ctor with a parameter, or the original with a default = 0 parameter and if 0 set null) allocate memory, that idea becomes:
Dealer tempDealer(1000); //constructor allocates the memory now, see? (you have to write that in)
Car tempCar; // default variables
Car *cars = tempDealer.getCarArray(); // this is valid now, due to above ^^

I can't stress enough that this should be a vector. hand rolled memory management inside classes is high risk code where it is easy to make mistakes both as you make it and again later if you edit it to reuse it/grow it. Trust me that the problems you are seeing already are the tip of an iceberg.
Last edited on
That makes a lot of sense, I was missing the setCarArray(newCarQuantity); function for the tempDealer.

Onto the
ends an destructor


This is deleting the vector I pass in main?

edit:

Yeah the use of vectors here would instrumentally more beneficial but sadly its required.

when I try to use the other type of ctor I get this type of error
 
(.text+0x749): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `tempDealer()' 


edit: I think this is because it tries to interpret it as a function. My mistake

edit 2:
I think I now know what I was doing wrong, I added this
1
2
3
4
5
6

for (int k = 0; k < vec.size(); ++k) {
        if(vec[k].getDealerNumber() == newCarToDealer){
            Dealer tempDealer(vec[k].getDealerName(),vec[k].getDealerNumber(),vec[k].getNumberOfCars());
            Car tempCar;
            Car *cars = vec[k].getCarArray();


whats funky now is the for loop has interesting errors with how it deals with multiple cars being added. But you helped me realize what my issue was!

What would the line look like to not overwrite the car array but add to it?
I'm hesitant to use vec.push_back(); because I am not adding another dealer, simply cars to the array. Would I still use vec.push_back()?

Marking issue as resolved, thank you a ton. I genuinely learned a lot about pointers and references through all this.
Last edited on
Topic archived. No new replies allowed.