Length of array in function argument

前端 未结 8 2026
终归单人心
终归单人心 2020-11-21 23:05

This is well known code to compute array length in C:

sizeof(array)/sizeof(type)

But I can\'t seem to find out the length of the array pass

8条回答
  •  轮回少年
    2020-11-21 23:49

    The array decays to a pointer when passed.

    Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.


    That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).

    Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?


    Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.

    You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.

提交回复
热议问题