Passing an array of structs in C

后端 未结 9 882
傲寒
傲寒 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:13

    Define struct Items outside of main. When passing an array to a function in C, you should also pass in the length of the array, since there's no way of the function knowing how many elements are in that array (unless it's guaranteed to be a fixed value).

    As Salvatore mentioned, you also have to declare (not necessarily define) any structs, functions, etc. before you can use them. You'd usually have your structs and function prototypes in a header file in a larger project.

    The below is a working modification of your example:

    #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;
    }
    

提交回复
热议问题