How do I find the length of an array?

前端 未结 27 3531
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

27条回答
  •  佛祖请我去吃肉
    2020-11-21 23:15

    Here is one implementation of ArraySize from Google Protobuf.

    #define GOOGLE_ARRAYSIZE(a) \
      ((sizeof(a) / sizeof(*(a))) / static_cast(!(sizeof(a) % sizeof(*(a)))))
    
    // test codes...
    char* ptr[] = { "you", "are", "here" };
    int testarr[] = {1, 2, 3, 4};
    cout << GOOGLE_ARRAYSIZE(testarr) << endl;
    cout << GOOGLE_ARRAYSIZE(ptr) << endl;
    

    ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling.

    Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t.

    This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.

提交回复
热议问题