gpt4 book ai didi

c - 数组 c 中声明的元素数

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:30 24 4
gpt4 key购买 nike

我在c中创建了一个静态数组

int array[15];

例如,我“填充”了数组的前 5 个元素。

这意味着我还有 10 个免费元素,对吧?

我应该怎么做才能知道我已经“使用”了数组的五个元素?我怎么知道我使用了多少个元素?

最佳答案

What should I do to know that I have already "used" five elements of my array? How would I know the number of elements that I have used?

有几个选项。

  1. 使用标记值指示已填充的元素。假设您使用 99999 作为标记值。如果数组的第 n 个元素的值为 99999,则您知道您已经填满了 n-1 个元素。

  2. 使用另一个变量来跟踪它。

    size_t numFilledElements = 0;

    for ( ... )
    {
    // Fill up an element

    // Increment the counter.
    ++numFilledElements;
    }

我个人的偏好是使用第二种方法。这样,您就不必担心哨兵值了。

关于c - 数组 c 中声明的元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36895562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com