简体   繁体   中英

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

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.

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

Either:

(*tempCar).make = "GM";

Or:

tempCar->make = "GM";

tempCar->vin = 1234

The explanation is quite simple : car* is a pointer on car . It's mean you have to use the operator -> to access data. By the way, car* must be allocated if you want to use it.

The other solution is to use a declaration such as car tempCar; . The car struct is now on the stack you can use it as long as you are in this scope. With this kind of declaration you can use tempCar.vin to access data.

Your tempCar is a pointer, then you have to allocate memory for it and assign like this:

tempCar = new car();
tempCar->vin = 1234;         
tempCar->make = "GM";
tempCar->year = 1999;
tempCar->fee = 20.5;

Otherwise declare tempCar in this way: car tempCar;

Change your car *temp to below line:

 car *tempCar = (car *)malloc(sizeof(car));

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

人们在使用new时要小心,这不是Java,它是C ++,当你没有参数时不要使用括号:tempCar = new car;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM