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

前端 未结 6 1778
情书的邮戳
情书的邮戳 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:24

    sizeof returns the size in bytes, which for an array is the number of items × the size of each item. To get the number of items divide by the size of one element.

    sizeof(races) / sizeof(races[0])
    

    Be careful with this. It will only work for arrays whose size is known at compile time. This will not work:

    void func(short int array[])
    {
        // DOES NOT WORK
        size_t size = sizeof(array) / sizeof(array[0]);
    }
    

    Here array is actually a short int * and sizeof(array) does not return the actual size of the array, which is unknown at compile time.

    This is one of many reasons to prefer std::vector or std::array to raw arrays in C++.

提交回复
热议问题