c++ - 我可以在 C++ 中确定数组的大小/长度而不必对其进行硬编码吗?

标签 c++ arrays

我基本上是在寻找某种“动态”方式将数组的大小/长度传递给函数。


我试过:

void printArray(int arrayName[])
{
    for(int i = 0 ; i < sizeof(arrayName); ++i)
    {
        cout << arrayName[i] << ' ';
    }
}

但我意识到它只考虑它的字节大小,而不考虑数组上有多少元素。


还有:

void printArray(int *arrayName)
{
    while (*arrayName)
    {
        cout << *arrayName << ' ';
        *arrayName++;    
    }
}

这至少打印了我的所有内容,但超出了我的预期,所以它实际上并没有按照我想要的方式工作。 我认为这是因为我没有确切地告诉它我需要它有多大,所以它“安全”地播放它并给我一些大尺寸并最终开始在我的数组中的最后一个元素之后打印我非常奇怪的整数。


所以我终于解决了这个问题,但我相信还有更好的东西!:

void printArray(int *arrayName)
{
    while (*arrayName)
    {
        if (*arrayName == -858993460)
        {
            break;
        }
        cout << *arrayName << ' ';
        *arrayName++;
    }
    cout << '\n';
}

程序运行几次后,我发现我输入的数组最后一个元素后面的值总是:-858993460,所以我让它在遇到这个值时中断 while 循环。


include <iostream>
include <conio.h>

using namespace std;

    // functions prototypes
void printArray (int arrayName[], int lengthArray);

    // global variables

    //main
int main ()
{
    int firstArray[] = {5, 10, 15};
    int secondArray[] = {2, 4, 6, 8, 10};
    printArray (firstArray,3);
    printArray (secondArray,5);

    // end of program
    _getch();
    return 0;
}

    // functions definitions
void printArray(int arrayName[], int lengthArray) 
{
    for (int i=0; i<lengthArray; i++)
    {
        cout << arrayName[i] << " ";
    }
    cout << "\n";
}

非常感谢。

最佳答案

TL;DR 答案:使用 std::vector .


But I realized it [sizeof()] only considers its bytesize and not how many elements are on the array.

这本身不是问题:您仍然可以使用 sizeof(array) / sizeof(array[0]) 获取数组的大小,但问题是当传递给函数时,数组会衰减为指向其第一个元素的指针,因此您只能得到 sizeof(T *)。 (T 是数组中元素的类型)。

关于 *arrayName++ :

This has at least printed me everything but more than what I expected

我什至不明白是什么启发了您以这种方式计算数组的大小。这段代码所做的只是递增数组中的第一个对象,直到它为零。

After running the program a few times I realized the value after the last element of the array that I have input is always: -858993460

这是一个糟糕的假设,它还依赖于未定义的行为。您无法真正确定数组第一个元素之后的内存中有什么,您甚至不应该访问它。


基本上,在 C++ 中,如果您想从函数中知道原始数组的大小,那么您必须手动跟踪它(例如添加一个额外的 size_t size 参数),因为数组的方式传递给函数(记住,它们“退化为”一个指针)。如果您想要更灵活的东西,请考虑使用 std::vector<int> (或您要存储的任何类型的对象)来自 C++ 标准库——它有一个 size()方法,这正是您想要的。

关于c++ - 我可以在 C++ 中确定数组的大小/长度而不必对其进行硬编码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637919/

相关文章:

arrays - 如何使用 Repa 在一定范围内获取数组切片

javascript - jQuery.InArray() 返回 -1 的问题

c++ - 如果在我的机器上 sizeof(long) == sizeof(long long),为什么它们不是同一类型?

c++ - 我怎样才能在 C++ 中做第二类构造函数?

c++ - 使用 LLVM 在 OSX 上将问题与 boost::program_options 联系起来

c++ - 错误 - C++ 中的 "throws different exceptions"

Ruby - 如何将字符串解析为哈希数组

c++ - 找出分数 a/b 的小数点后第 k 位,其中 a,b,k 是非常大的整数(小于 10e18)

c - 遍历数组 MASM 中的元素并对其求平均值

javascript - 列表 JS 对象数组