C: finding the number of elements in an array[]

前端 未结 11 1852
陌清茗
陌清茗 2020-12-16 14:31

In C: How do you find the number of elements in an array of structs, after sending it to a function?

int main(void) {
  myStruct array[] = { struct1, struct2         


        
11条回答
  •  旧时难觅i
    2020-12-16 15:19

    As an example to your solution:

    Given

    struct contain {
    char* a;        //
    int allowed;    //
    
    struct suit {
       struct t {
              char* option;
              int count;
       } t;
    
       struct inner {
              char* option;
              int count;
       } inner;
    } suit;
    };
    

    // eg. initialized

         struct contain structArrayToBeCheck[] = {
        {
            .a = "John",
            .allowed = 1,
    
            .suit = {
                .t = {
                    .option = "ON",
                    .count = 7
                },
    
                .inner = {
                    .option = "OFF",
                    .count = 7
                }
            }
        },
        {
            .a = "John",
            .allowed = 1,
    
            .suit = {
                .t = {
                    .option = "ON",
                    .count = 7
                },
    
                .inner = {
                    .option = "OFF",
                    .count = 7
                }
            }
        },
        {
            .a = "John",
            .allowed = 1,
    
            .suit = {
                .t = {
                    .option = "ON",
                    .count = 7
                },
    
                .inner = {
                    .option = "OFF",
                    .count = 7
                }
            }
        },
        {
            .a = "John",
            .allowed = 1,
    
            .suit = {
                .t = {
                    .option = "ON",
                    .count = 7
                },
    
                .inner = {
                    .option = "OFF",
                    .count = 7
                }
            }
        }
    
    };
    

    in main()

    printf("Number of Struct within struct array: %d \n", sizeof(structArrayToBeCheck)/sizeof(struct contain));
    

    gives you the correct answer.

提交回复
热议问题