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

前端 未结 11 1832
陌清茗
陌清茗 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:15

    When you use sizeof in main, it's evaluating the array, and gives the size of the actual array.

    When you use sizeof in f, you've passed the name of the array as an argument to a function, so it has decayed to a pointer, so sizeof tells you about the size of a pointer.

    Generally speaking, if you pass an array to a function, you need to either write the function to only work with one specific size of array, or explicitly pass the size of array for it to work with on a particular invocation.

提交回复
热议问题