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开发者_如何学Python 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;
People, be careful when using new, this is not Java, it's C++, don't use parentheses when you don't have parameters: tempCar = new car;
精彩评论