[英]Passing an array of structs in 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 <stdio.h>
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);
為什么不使用將指向數組的指針傳遞給需要它的方法?
如果你想要相同的struct數組,那么你應該使用指向數組的指針,而不是像創建副本那樣傳遞數組。
void ReadFile(struct Items * items);
你叫它的地方
struct Items myItems[10];
ReadFile(myItems);
需要小心指針......
你幾乎必須使用指針。 你的功能看起來像這樣:
void ReadFile(Items * myItems, int numberOfItems) {
}
你需要使用指向數組的指針,之后很容易訪問它的成員
void ReadFile(Items * items);
應該管用。
好吧,當你像你一樣傳遞一個結構時,它實際上在函數中創建了它的本地副本。 因此,無論您如何在ReadFile
修改它,它都不會影響您的原始結構。
我不確定不同的方法,這可能無法解答您的問題,但我建議您嘗試指針。 你肯定會在C / C ++中大量使用它們。 一旦掌握了它們,它們就會非常強大
你試圖聲明你的功能如下:
void ReadFile(struct Items[])
可能會有所幫助: http : //www.daniweb.com/software-development/cpp/threads/105699
而不是你的聲明,以這種方式聲明:
typedef struct {
char code[10];
char description[30];
int stock;
}Items;
和那樣的功能:
void ReadFile(Items *items);
使用typedef可以定義一個新類型,因此每次都不需要使用單詞“struct”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.