无法通过引用将 typedef 结构传递给函数
Can't pass typedef struct to function by reference
我正在尝试通过引用将自定义类型对象传递给函数,但我不知道自己做错了什么。我阅读了 How do you pass a typedef struct to a function? 以及其他参考资料,可以发誓我已经在这样做了。我清除了我正在做的所有其他事情,甚至这个简单的代码也会抛出 5 个错误。帮助我,Stackexchange;你是我唯一的希望!
目标只是能够更改对象数组中的值。
#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);
}
当我尝试 运行 时,我得到了这个错误和 4 个类似的错误:
test2.c:10:3: error: request for member ‘byte’ in something not a structure or union
a.byte[0] = value;
a
是一个指针类型,所以你需要取消引用它才能使用它。通常这是用箭头运算符完成的:
a->byte[i] = 0;
由于这只是一个字节数组,您还可以快速 "zero" 它:
memset(a, 0, 10);
尽管鉴于 10
在您的代码中的重要性,您应该将其编码为常量或 #define
。
当您通过引用传递值时,您需要使用星号来访问结构的所有字段,例如:
(*a).byte[0] = value;
很高兴你有 -> 作为快捷方式,所以这将是:
a->byte[0] = value;
也不要忘记在调用 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);
}
我正在尝试通过引用将自定义类型对象传递给函数,但我不知道自己做错了什么。我阅读了 How do you pass a typedef struct to a function? 以及其他参考资料,可以发誓我已经在这样做了。我清除了我正在做的所有其他事情,甚至这个简单的代码也会抛出 5 个错误。帮助我,Stackexchange;你是我唯一的希望!
目标只是能够更改对象数组中的值。
#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);
}
当我尝试 运行 时,我得到了这个错误和 4 个类似的错误:
test2.c:10:3: error: request for member ‘byte’ in something not a structure or union
a.byte[0] = value;
a
是一个指针类型,所以你需要取消引用它才能使用它。通常这是用箭头运算符完成的:
a->byte[i] = 0;
由于这只是一个字节数组,您还可以快速 "zero" 它:
memset(a, 0, 10);
尽管鉴于 10
在您的代码中的重要性,您应该将其编码为常量或 #define
。
当您通过引用传递值时,您需要使用星号来访问结构的所有字段,例如:
(*a).byte[0] = value;
很高兴你有 -> 作为快捷方式,所以这将是:
a->byte[0] = value;
也不要忘记在调用 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);
}