How to reliably get size of C-style array?

后端 未结 10 1964
广开言路
广开言路 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:09

    I also agree that Corwin's method above is very good.

    template 
    void foo(int (&x)[N]) 
    {
        std::cerr << N;
    }
    

    I don't think anybody gave a really good reason why this is not a good idea.
    In java, for example, we can write things like:

    int numbers [] = {1, 2, 3, 4};
    for(int i = 0; i < numbers.length(); i++)
    {
       System.out.println(numbers[i]+"\n");
    }
    

    In C++ it would be nice instead of saying

    int numbers [] = {1, 2, 3, 4};
    int size = sizeof(numbers)/sizeof(int);
    for(int i = 0; i < size; i++)
    {
        cout << numbers[i] << endl;
    }
    

    We could take it a step further and go

    template 
    int size(int (&X)[N])
    {
       return N;
    }
    

    Or if that causes problems I suppose you could write explicitly:

    template < int N >
    int size(int (&X)[N])
    {
       int value = (sizeof(X)/sizeof(X[0]));
       return value;
    }
    

    Then we just have to go in main:

    int numbers [] = {1, 2, 3, 4};
    for(int i = 0; i < size(numbers); i++)
    {
       cout << numbers[i] << endl;
    }
    

    makes sense to me :-)

提交回复
热议问题