How do you pass a typedef struct to a function?

坚强是说给别人听的谎言 提交于 2020-02-28 08:12:32

问题


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];

回答1:


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);



回答2:


A type introduced with typedef is an alias that can be used for a real type.

For example:

typedef struct some_struct { ... } some_type_name;

Now you can use some_type_name instead of struct some_struct.

So when declaring a function which takes a structure of this "type" you use the type like any other type:

void some_function(some_type_name var) { ... }

In some_function as defined above, you can use var like a normal structure variable.

To define a function taking an array (or a pointer) to this type, that's equally simple:

void some_function(some_type_name *pointer) { ... }


来源:https://stackoverflow.com/questions/16159712/how-do-you-pass-a-typedef-struct-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!