[英]Passing an element of an array of structs in C
我試圖傳遞我制作的20個“數據庫”結構之一
這是我的函數“添加”的原型
void add(struct database test);
我想通過數據庫結構,現在我將其稱為“測試”
這是我的數據庫結構
struct database
{
char ID[6];
char Duration[3];
};
main()
{
char menu;
struct database employee[20]; // I make 20 employee variables
int a = 0; /*A counter I use to edit certain structs
ie a=2 "employee[a]" = "employee[2]" */
然后,我像這樣調用該函數:
add(employee[a]);
a++; /*Once it exits this I want it to go to the next employee
variable so I increment the counter */
實際功能如下所示:
void add(struct database test)
{
static int a = 0;
printf("\nPlease enter a 5 digit employee number: ");
scanf("%s", test[a].ID);
a++
}
在執行此操作時出現錯誤:
錯誤E2094 Assignment.c 64:函數add(database)中類型為'int'的參數的類型'database'中未實現'operator +'
它說錯誤在
scanf("%s", test[a].ID);
在此先感謝您提供的任何幫助,如果出現格式錯誤,我將致歉,仍在學習使用堆棧溢出功能,非常抱歉!
add(struct database test)
聲明一個struct database
作為參數。 這不是一個數組,因此無法對其進行索引。
所以
test[a]
是無效的。
另外, int a
內部add()
是從不同int a
中所定義main()
在add()
內部,后者a
被前者a
隱藏。
另外^ 2,您還向add()
傳遞了main()
聲明的數組元素的副本。 因此,當從add()
返回時,為在側面add()
中進行test
所做的任何修改都會丟失。 它們在main()
的數組中不可見。
這是您需要做的以使其正確的操作:
void add(struct database* test)
{
printf("\nPlease enter a 5 digit employee number: ");
scanf("%s",test->ID);
}
int main()
{
...
int a;
struct database employee[20];
for (a=0; a<sizeof(employee)/sizeof(*employee); a++)
add(&employee[a]); // or add(employee+a);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.