[英]How to modify struct passed by reference?
I'm passing a struct to a function by reference since I want to modify the struct inside the function. 我要通过引用将结构传递给函数,因为我想在函数内部修改结构。 However, the compiler keeps giving me "Error C1421: Undefined class/struct/union" at "++kpad.pin_chars;".
但是,编译器始终在“ ++ kpad.pin_chars;”处给我“错误C1421:未定义的类/结构/联合”。 What am I missing?
我想念什么? Here's my test code:
这是我的测试代码:
struct Keypad{
int pin_chars;
};
void check_keypad(struct Keypad *kpad);
void main(void){
struct Keypad kpad;
kpad.pin_chars = 0;
check_keypad(&kpad);
}
void check_keypad(struct Keypad *kpad){
++kpad.pin_chars;
}
You are passing a pointer, using the struct Keypad *kpad
syntax. 您正在使用
struct Keypad *kpad
语法传递指针。 That's the *
part. 那是
*
部分。
When you are passing a pointer, you cannot use "dot" to access a member without first dereferencing the pointer. 传递指针时,必须先取消对指针的引用 ,才能使用“点”访问成员。 You must dereference or use "arrow" (
->
) as your operator: 您必须取消引用或使用“ arrow”(
->
)作为运算符:
++ *kpad.pin_chars
or 要么
++kpad->pin_chars
In general, when using pointers the arrow syntax is the preferred approach. 通常,在使用指针时,箭头语法是首选方法。
Edit: 编辑:
It's worth pointing out the precedence of the various operators involved. 值得指出的是所涉及的各种运算符的优先级 。 Postfix
++
(and --
) have the same precedence as .
Postfix
++
(和--
)的优先级与相同.
and ->
, but would bind to the member in ptr->member++
due to location, whereas prefix ++
(and --
) have a lower precedence than .
和
->
,但由于位置原因会绑定到ptr->member++
,而前缀++
(和--
)的优先级低于.
and ->
, and so bind to the result of the member-access expression as a result of precedence, not position. 和
->
,因此绑定到成员访问表达式的结果是优先级的结果,而不是位置。
You get the result in two slightly different ways. 您可以通过两种略有不同的方式获得结果。
Since you passed a parameter by address, you need to de-reference it to get to its value. 由于您是按地址传递参数的,因此您需要取消对其的引用才能获取其值。 The following code works:
以下代码有效:
void check_keypad(struct Keypad *kpad){
++((*kpad).pin_chars);
}
C provides another format for the same purpose: C提供了另一种用于相同目的的格式:
void check_keypad(struct Keypad *kpad){
++(kpad->pin_chars);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.