c++ sizeof(array) return twice the array's declared length

前端 未结 6 1781
情书的邮戳
情书的邮戳 2020-12-02 02:47

I have a section of code in which two array are declared with sizes of 6 and 13, but when \'sizeof()\' is used the lengths are returned as 12 and 26.

#includ         


        
6条回答
  •  忘掉有多难
    2020-12-02 03:18

    The sizeof operator returns the size in bytes required to represent the type (at compile time).

    double array[10]; // type of array is: double[10]
    

    sizeof(array) has the same meaning as sizeof(double[10]), which is equal to:

    sizeof(double) * 10
    

    It's an array that can hold 10 double values. sizeof(array[0]) means: size of a single element in array, which is the same as sizeof(double) here. To get the actual number of elements, you have to divide the size of the array by the size of a single element:

    size_t num_elem = sizeof(array) / sizeof(array[0]);
    

    However, this doesn't work on pointers!

    double* p = array;
    

    sizeof(p) actually translates to sizeof(double*). Its size has nothing to do with the size of double or the size of the array it's pointing to. Instead, it's the size required to store the address to a memory location (32 bits on a 32bit operating). The information about the number of elements is lost!

    If you want to safely get the number of elements in an array, you can use this template:

    template
    size_t inline static_arrlen(T (&)[N]) {
        return N;
    }
    

    At compile-time, it deduces the type T and number of elements N, returning N.

    size_t num_elem = static_arrlen(array); // T=double, N=10
    

    If you're trying to get the array size from a pointer, it won't compile:

    static_arrlen(p); // ERROR: could not deduce template argument 
                      // for 'T (&)[N]' from 'double *'
    

提交回复
热议问题