How to reliably get size of C-style array?

后端 未结 10 1963
广开言路
广开言路 2020-11-29 09:37

How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof, but it doesn\'t work in the foo function

相关标签:
10条回答
  • 2020-11-29 10:15

    c provides no native support for this. Once an array is passed out of its declared scope, its size is lost.

    You can pass the size with the array. You can even bundle them into a structure if you always to to keep the size, though you'll have some bookkeepping overhead with that.

    0 讨论(0)
  • 2020-11-29 10:19

    Since c++11, there is a very convenient way:

    static const int array[] = { 1, 2, 3, 6 };
    int size = (int)std::distance(std::begin(array), std::end(array))+1;
    
    0 讨论(0)
  • 2020-11-29 10:23

    An array expression will have its type implicitly converted from "N-element array of T" to "pointer to T" and its value will be the address of the first element in the array, unless the array expression is the operand of either the sizeof or address-of (&) operators, or if the array expression is a string literal being used to initialize another array in a declaration. In short, you can't pass an array to a function as an array; what the function receives is a pointer value, not an array value.

    You have to pass the array size as a separate parameter.

    Since you're using C++, use vectors (or some other suitable STL container) instead of C-style arrays. Yes, you lose the handy shorthand syntax, but the tradeoff is more than worth it. Seriously.

    0 讨论(0)
  • 2020-11-29 10:23

    You need to pass the size along with the array, just like it is done in many library functions, for instance strncpy(), strncmp() etc. Sorry, this is just the way it works in C:-).

    Alternatively you could roll out your own structure like:

    struct array {
        int* data;
        int size;
    };
    

    and pass it around your code.

    Of course you can still use std::list or std::vector if you want to be more C++ -ish.

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