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

前端 未结 11 1833
陌清茗
陌清茗 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条回答
  •  温柔的废话
    2020-12-16 15:02

    You must pass that data as a separate parameter to the function. In C and C++ as soon as an array is passed to a function the array degenerates into a pointer. Pointers have no notion of how many elements are in the array they point to.

    A common way to get the size is to declare the array and then immediately get the array element count by dividing the total size by the size of one element. Like this:

    struct my_struct my_struct_array[] = {
     {"data", 1, "this is data"},
     {"more data", 2, "this is more data"},
     {"yet more", 0, "and again more data"}
    };
    const size_t my_struct_array_count = sizeof(my_struct_array)/sizeof(my_struct_array[0]);
    

提交回复
热议问题