你如何将一个typedef结构传递给一个函数? [英] How do you pass a typedef struct to a function?
问题描述
目前我正在尝试
void avg(everything)
但是,这给了我错误:
错误:下标值既不是数组也不是指针
当我今天早些时候得到这个错误时,这是因为我没有不能将2D数组正确传递给函数。所以我想这是相同的,但我无法找到正确的格式来传递它。
这是我的typedef:
typedef结构结构
{
字符名称[13] [9];
int分数[13] [4];
平均浮动[13];
char char [13];
}的东西;
这是我的typedef数组:
填充所有内容[13];
解决方案在函数签名中,您需要指定类型,而不是要传入的变量的具体名称。此外,如果要传递数组,则需要传递一个指针(您应该可以通过指针传递结构,否则将会创建一个数据副本每次你调用函数)。因此,你的函数应该看起来像:
void avg(stuff * s);
但是,C数组也没有长度的概念。因此,您应该始终将数组的长度传递给函数:
void avg(stuff * s,size_t len) ;
然后你可以这样调用它:
avg(everything,13);
另外,如果函数不以任何方式修改数据,则应该通过指定该参数是
const
:void avg(const stuff * s ,size_t len);
At the moment I'm trying
void avg(everything)
But that gives me the error:
error: subscripted value is neither array nor pointer
And when I got this error earlier today it was because I wasn't passing a 2D array to the function properly. So I figure this is the same but I can't find the correct format to pass it in.
This is my typedef:
typedef struct structure { char names[13][9]; int scores[13][4]; float average[13]; char letter[13]; } stuff;
And this is my typedef array:
stuff everything[13];
解决方案In the function signature, you need to specify the type, not the specific name of a variable you want to pass in. Further, if you want to pass an array, you need to pass a pointer (you should probably be passing structs by pointers anyway, otherwise a copy of the data will be made each time you call the function). Hence you function should look like:
void avg(stuff* s);
However, C arrays also have no concept of length. Hence, you should always pass in the length of the array to the function:
void avg(stuff* s, size_t len);
You'd then call this as follows:
avg(everything, 13);
Also, if the function doesn't modify the data in any way, you should signify this by specifying that the parameter is
const
:void avg(const stuff* s, size_t len);
这篇关于你如何将一个typedef结构传递给一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!