Passing an array of structs in C

后端 未结 9 869
傲寒
傲寒 2020-12-01 16:33

I\'m having trouble passing an array of structs to a function in C.

I\'ve created the struct like this in main:

int main()
{
    struct Items
    {
          


        
9条回答
  •  温柔的废话
    2020-12-01 17:23

    The function won't know that the type struct Items exists if you declare it only locally inside the main function body scope. So you should define the struct outside:

    struct Item { /* ... */ };
    
    void ReadFile(struct Items[]);   /* or "struct Item *", same difference */
    
    int main(void)
    {
      struct Item my_items[10];
      ReadFile(my_items);
    }
    

    This is dangerous of course since ReadFile has no idea how big the array is (arrays are always passed by decay-to-pointer). So you would typically add this information:

    void ReadFile(struct Items * arr, size_t len);
    
    ReadFile(my_items, 10);
    

提交回复
热议问题