Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointers. How to assign value to a pointer struct?

I have the following struct:

typedef struct{
    int vin;
    char* make;
    char* model;
    int year;
    double fee;
}car;

Then I create a pointer of type car

car *tempCar;

How do I assign values to the tempCar? I'm having trouble

        tempCar.vin = 1234;         
        tempCar.make = "GM";
        tempCar.year = 1999;
        tempCar.fee = 20.5;

Compiler keeps saying tempCar is of type car*. I'm not sure what I'm doing wrong

like image 792
user69514 Avatar asked Feb 24 '10 21:02

user69514


2 Answers

You need to use the -> operator on pointers, like this:

car * tempCar = new car();
tempCar->vin = 1234;
tempCar->make = "GM";
//...
delete tempCar;

Also, don't forget to allocate memory for tempCar if you're using a pointer like this. That's what 'new' and 'delete' do.

like image 83
Aric TenEyck Avatar answered Nov 20 '22 08:11

Aric TenEyck


You have to dereference the pointer first (to get the struct).

Either:

(*tempCar).make = "GM";

Or:

tempCar->make = "GM";
like image 16
Seth Avatar answered Nov 20 '22 07:11

Seth