通过引用传递数组并找到其大小

问题描述 投票:0回答:1

如何通过引用传递数组并查找其长度。目前我有下面的代码,这似乎没有打印实际的数组大小。我们可以使用 sizeof() 或 size() 来打印数组大小吗?

#include<iostream>
using namespace std;

int ArrayLength(int &arr){
    int l = 0, h, mid;
    h = sizeof(arr)/sizeof(int);
    
    return h;
}

int main(){
    int len, value;
    cout << "Enter the length of the array: ";
    cin >> len;
    int *arr = new int[len];
    cout << "Enter the elements of the array: ";
    for(int i = 0; i < len; i++){
        cin >> arr[i];
    }
    cout << "You entered: ";
    for(int i = 0; i < len; i++){
        cout << arr[i] << " ";
    }
    cout << endl;
    value = ArrayLength(*arr);
    cout << value << endl;
}

尝试使用 sizeof()

arrays pointers
1个回答
0
投票

与其他语言不同,C++中数组的长度不与数组一起存储。它存储在堆的内存管理器中。如果使用 new 进行分配,则没有标准方法来告知大小,因为每个工具链都有不同的堆管理。

您可以使用 std::vector,而不是使用 new 动态调整大小。如果你这样做了,那么大小就是 .size() 成员。

© www.soinside.com 2019 - 2024. All rights reserved.