Length of array in function argument

前端 未结 8 1901
终归单人心
终归单人心 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

    As stated by @Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof() macro useful - it does the equivalent of what you've done ;)

    0 讨论(0)
  • 2020-11-21 23:50

    Regarding int main():

    According to the Standard, argv points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).

    That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };.

    Hence, size calculation is performed by a function which is a trivial modification of strlen().

    argc is only there to make argv length calculation O(1).

    The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.

    0 讨论(0)
提交回复
热议问题