views:

356

answers:

6

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

+4  A: 

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.

Niklaos
Declaring an instance (as with **car tempCar;**) can easily be on the stack and isn't necessarily *static*
NVRAM
I know my sentence wasn't clear, i meant static allocation in opposition to a dynamic allocation :) thanks
Niklaos
+7  A: 

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

Either:

(*tempCar).make = "GM";

Or:

tempCar->make = "GM";
Seth
+9  A: 

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.

Aric TenEyck
+1 for the reminder to alloc the memory
quixoto
You don't necessarily have to allocate memory here. The pointer may be pointing at a local struct on the stack. `car ferrari; tempCar = `
Seth
+1  A: 

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;

coelhudo
A: 

What everybody else said.

JimDaniel
I don't think it works that way. :p
GMan
A: 

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;

Chololennon
Why "be careful"? It's a style issue and I definitely disagree: use the parens.
NVRAM
Not a style issue. With parenthesis, the members in a POD type will be default-constructed. Parenthesis are usually preferred, in my experience.
GMan