C++ 指针。如何为指针结构赋值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2329581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Pointers. How to assign value to a pointer struct?
提问by user69514
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 赋值?我有麻烦
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
编译器一直说 tempCar 是 car* 类型。我不确定我做错了什么
回答by Aric TenEyck
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.
另外,如果您使用这样的指针,请不要忘记为 tempCar 分配内存。这就是“新建”和“删除”的作用。
回答by Seth
You have to dereference the pointer first (to get the struct).
您必须首先取消引用指针(以获取结构)。
Either:
任何一个:
(*tempCar).make = "GM";
Or:
或者:
tempCar->make = "GM";
回答by Nicolas Guillaume
tempCar->vin = 1234
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.
解释很简单:car*
是一个指针car
。这意味着您必须使用运算符->
来访问数据。顺便说一下,car*
如果你想使用它,必须分配。
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.
另一种解决方案是使用诸如car tempCar;
. 该car
结构现在在堆栈上,只要您在此范围内就可以使用它。通过这种声明,您可以tempCar.vin
用来访问数据。
回答by coelhudo
Your tempCar is a pointer, then you have to allocate memory for it and assign like this:
你的 tempCar 是一个指针,然后你必须为它分配内存并像这样分配:
tempCar = new car();
tempCar->vin = 1234;
tempCar->make = "GM";
tempCar->year = 1999;
tempCar->fee = 20.5;
Otherwise declare tempCar in this way: car tempCar;
否则以这种方式声明 tempCar: car tempCar;
回答by hmims
Change your car *temp to below line:
将您的汽车 *temp 更改为以下行:
car *tempCar = (car *)malloc(sizeof(car));
tempCar->vin = 1234;
tempCar->make = "GM";
tempCar->year = 1999;
tempCar->fee = 20.5;
回答by hmims
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;
各位,用new的时候要小心,这不是Java,是C++,没有参数的时候不要用括号:tempCar = new car;