在C中传递一组结构
我无法将结构数组传递给C中的函数。
我在main中创建了这样的结构:
int main() { struct Items { char code[10]; char description[30]; int stock; }; struct Items MyItems[10]; }
然后我访问它: MyItems[0].stock = 10;
等等
我想将它传递给像这样的函数:
ReadFile(MyItems);
该函数应该读取数组,并能够编辑它。 然后我应该能够从其他函数访问相同的数组。
我已经尝试了大量的声明,但没有一个能够奏效。 例如
void ReadFile(struct Items[10])
我已经浏览了其他问题,但问题是它们都是完全不同的,使用typedef和asterisks。 我的老师还没有教过我们指针,所以我想用我所知道的方法来做。
有任何想法吗? :S
编辑:Salvatore的答案是在我将原型修复为:
void ReadFile(struct Items[10]);
struct Items { char code[10]; char description[30]; int stock; }; void ReadFile(struct Items items[10]) { ... } void xxx() { struct Items MyItems[10]; ReadFile(MyItems); }
这在我的编译器中运行良好。 你用的是什么编译器? 你得到了什么错误?
记得在你的函数之前声明你的结构,否则它将永远不会工作。
在main之外定义struct Items
。 当将数组传递给C中的函数时,您还应传入数组的长度,因为该函数无法知道该数组中有多少元素(除非它保证是固定值)。
正如Salvatore所提到的,在使用它们之前,您还必须声明(不一定定义)任何结构,函数等。 您通常在较大的项目中的头文件中包含结构和函数原型。
以下是您的示例的工作修改:
#include struct Items { char code[10]; char description[30]; int stock; }; void ReadFile(struct Items items[], size_t len) { /* Do the reading... eg. */ items[0].stock = 10; } int main(void) { struct Items MyItems[10]; ReadFile(MyItems, sizeof(MyItems) / sizeof(*MyItems)); return 0; }
如果仅在main
函数体范围内本地声明它,则该函数将不知道类型struct Items
存在。 所以你应该在外面定义结构:
struct Item { /* ... */ }; void ReadFile(struct Items[]); /* or "struct Item *", same difference */ int main(void) { struct Item my_items[10]; ReadFile(my_items); }
这当然很危险,因为ReadFile
不知道数组有多大(数组总是通过衰减到指针传递)。 所以你通常会添加这些信息:
void ReadFile(struct Items * arr, size_t len); ReadFile(my_items, 10);
你几乎必须使用指针。 你的function看起来像这样:
void ReadFile(Items * myItems, int numberOfItems) { }
您需要使用指向数组的指针,之后很容易访问其成员
void ReadFile(Items * items);
应该管用。
好吧,当你像你一样传递一个结构时,它实际上在函数中创建了它的本地副本。 因此,无论您如何在ReadFile
修改它,它都不会影响您的原始结构。
我不确定不同的方法,这可能无法解答您的问题,但我建议您尝试指针。 你肯定会在C / C ++中大量使用它们。 一旦掌握了它们,它们就会非常强大
你试图声明你的function如下:
void ReadFile(struct Items[])
可能会有所帮助: http : //www.daniweb.com/software-development/cpp/threads/105699
而不是你的声明,以这种方式声明:
typedef struct { char code[10]; char description[30]; int stock; }Items;
和那样的function:
void ReadFile(Items *items);
使用typedef可以定义一个新类型,因此每次都不需要使用单词“struct”。
为什么不使用将指向数组的指针传递给需要它的方法?
如果你想要相同的struct数组,那么你应该使用指向数组的指针,而不是像创建副本那样传递数组。
void ReadFile(struct Items * items);
你叫它的地方
struct Items myItems[10]; ReadFile(myItems);
需要小心指针……