c++ - 将整数数组传递给函数时计算元素数量时得到不同的结果

标签 c++

我只是想获取整数数组中元素的数量。以下是代码:

#include <iostream>

int unsorted[] = {9,8,7,6,5,4,3,2,1};

void PrintArrayAndSize(int arr[]);


int main(int argc, const char * argv[]) 
{
    // insert code here...

    long size = *(&unsorted + 1) - unsorted;

    std::cout<<"no of elements = " << size <<"\n";//sizeof(int);

    PrintArrayAndSize(unsorted);

    return 0;
}


void PrintArrayAndSize(int arr[])
{

    for(int i = 0 ; i < 9 ; i++)

        std::cout<<arr[i]<<"\n";

    long size = *(&arr + 1) - arr;

    std::cout<<"no of elements = " << size <<"\n";//sizeof(int);
}

以下是输出。它是同一个数组,但是当我在 main 中计算大小时,我得到了正确的输出。当我将数组传递给函数并进行计算时,我得到了一些其他结果。

元素数 = 9

9 8个 7 6个 5个 4个 3个 2个 1

元素数 = 35182156444984

程序以退出代码结束:0

最佳答案

对于参数,数组作为指针(指向数组的第一个元素)传递。即使使用例如int arr[]。编译器将其视为 int *arr

这意味着 &arr 是一个指向指针的指针,而不是指向数组的指针。

如果您想让函数知道数组的大小,您应该始终将其作为参数传递。

或者,由于您使用的是 C++,因此您可以使用 std::array 而不是普通的 C 样式数组。或 std::vector .

或者使用模板能够传递对数组的引用并自动扣除数组大小(这也可用于 std::array)。

所以我的建议是你做类似的事情

template<size_t N>
void PrintArrayAndSize(std::array<int, N> const& arr)
{
    for (auto value : arr)
        std::cout << value << '\n';

    std::cout << "Array size is " << arr.size() << '\n';
}

int main()
{
    std::array<int, 9> a = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
    PrintArrayAndSize(a);
}

关于c++ - 将整数数组传递给函数时计算元素数量时得到不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606963/

相关文章:

c++ - 矩阵循环移位

c++ - 与类型转换运算符一起使用时条件运算符 "?:"的编译器错误

c++ - 格式化宏以使用单行 if 语句

c++ - 为什么 clang 编译器标志的顺序会影响生成的二进制大小?

c++ - 自动提供getter和setter函数的基类C++

c++ win32更改应用程序显示名称

c++ - 项目中可用的本地头文件,但 make 给出 No such file or directory 错误

c++ - Opengl视频纹理

c# - C# 中泛型类型的缺点

c++ - 检测程序集是否可用