[英]Can't pass typedef struct to function by reference
I'm trying to pass a custom type object to a function by reference, and I can't figure out what I could be doing wrong. 我正在尝试通过引用将自定义类型对象传递给函数,但我无法弄清楚自己可能做错了什么。 I read How do you pass a typedef struct to a function?
我读了如何将typedef结构传递给函数? as well as other references and could swear I'm already doing exactly that.
以及其他参考资料,并且可以发誓我已经做到了。 I cleared out everything else I'm doing and even this spartan code throws 5 errors.
我清除了我正在做的所有其他事情,即使是这段spartan代码也会引发5个错误。 Help me, Stackexchange;
帮我,Stackexchange; You're my only hope!
你是我唯一的希望!
The goal is simply to be able to alter the values in the array in the object. 目的只是为了能够更改对象数组中的值。
#include <stdio.h>
#include <math.h>
typedef struct structure {
char byte[10];
char mod;
} complex;
void simpleInit (complex *a, char value) {//put the value in the first byte and zero the rest
a.byte[0] = value;
char i;
for (i = 1; i < 10; ++i) {
a.byte[i] = 0;
}
a.mod = 1;
}
void main () {
complex myNumber;
char value = 6;
simpleInit (myNumber, value);
}
When I attempt to run this I get this error and 4 similar: 当我尝试运行此命令时,出现此错误和4个类似的错误:
test2.c:10:3: error: request for member 'byte' in something not a structure or union
test2.c:10:3:错误:请求成员“字节”的内容不是结构或联合
a.byte[0] = value;
a.byte [0] =值;
a
is a pointer type, so you need to de-reference it to use it. a
是一个指针类型,所以你需要去参考它使用它。 Typically that's done with the arrow operator: 通常,这是通过箭头运算符完成的:
a->byte[i] = 0;
Since this is just an array of bytes you can also quickly "zero" it: 由于这只是一个字节数组,因此您也可以快速将其“归零”:
memset(a, 0, 10);
Though given how important 10
is in your code you should codify that in a constant or a #define
. 尽管给出了
10
在代码中的重要性,但您应该将其编码为常数或#define
。
When you pass a value by reference you need to use asterisk to access al fields of the structure, for example: 通过引用传递值时,需要使用星号访问结构的al字段,例如:
(*a).byte[0] = value;
Happily you have -> as a shortcut, so this will be: 幸运的是,您有->作为快捷方式,因此它将是:
a->byte[0] = value;
Also do not forget to call the & (address of) operator when you call simpleInit
. 同样,当您调用
simpleInit
时,请不要忘记调用&(地址)运算符。
#include <stdio.h>
#include <math.h>
typedef struct structure
{
char byte[10];
char mod;
} complex;
void simpleInit (complex *a, char value)
{
char i;
a->byte[0] = value;
for (i = 1; i < 10; ++i) {
a->byte[i] = 0;
}
a->mod = 1;
}
int main()
{
complex myNumber;
char value = 6;
simpleInit (&myNumber, value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.