c++ - 局部数组长度与从函数调用时不同

标签 c++ arrays c++11 decltype

在下面的代码中,std::extent<decltype(columns)>::value计算给定数组的长度。但是,当数组是函数参数时,编译器的行为方式不同。有人可以帮我解决一下吗?

输出:

local array length: 5

function array length: 0

代码:

#include <iostream>
#include <string>

void showcolumns_num(std::string columns[])
{
    int columns_num=std::extent<decltype(columns)>::value;
    std::cout<<"function array length: "<<columns_num<<std::endl;
}


int main()
{
    std::string column_list[]={"col1","col2","col3","col4","col5"};

    // local calculation of column number
    int columns_num=std::extent<decltype(column_list)>::value;
    std::cout<<"local array length: "<<columns_num<<std::endl;

    // function calculation of column number
    showcolumns_num(column_list);

    return 0;
}

最佳答案

您必须通过引用传递数组以避免指针衰减从而丢失大小信息:

template <std::size_t N>
void showcolumns_num(std::string (&columns)[N])

Live example .

关于c++ - 局部数组长度与从函数调用时不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28317624/

相关文章:

c++11 - 使用 CXX_FLAGS 构建 Eigen3

c++ - 在 C++ 中将智能指针放入类数据(作为类成员)的正确方法是什么?

c++ - Monotouch : Adding . 资源,gcc 错误

java - 从用户输入的值中单独获取数组元素

python - (A, B) 和 (C,) 之间的 Minkowski 距离

c - 调整二维动态分配表大小时出现段错误

c++ - Unique_ptr 自动销毁魔法

c++ - C++11 中使用模板参数的递归可变参数 void 函数

c++ - CandidateVotes.exe : 0xC0000005: Access violation reading location 0x00000000 中的 0x50E6F1C0 (ucrtbased.dll) 抛出异常

c++ - 如何在 C++ 中创建一个构造函数来创建线程开始运行时应该返回的 pthread