如何找到数组中的元素数? [英] How can I find the number of elements in an array?

查看:31
本文介绍了如何找到数组中的元素数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 int 数组,我需要找到其中的元素数.我知道它与 sizeof 有关,但我不确定如何准确使用它.

I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I'm not sure how to use it exactly.

推荐答案

如果你的数组在范围内,你可以使用 sizeof 来确定它的大小(以字节为单位)并使用除法来计算元素:

If you have your array in scope you can use sizeof to determine its size in bytes and use the division to calculate the number of elements:

#define NUM_OF_ELEMS 10
int arr[NUM_OF_ELEMS];
size_t NumberOfElements = sizeof(arr)/sizeof(arr[0]);

如果您接收一个数组作为函数参数或在堆中分配一个数组,则无法使用 sizeof 确定其大小.您必须以某种方式存储/传递尺寸信息才能使用它:

If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof. You'll have to store/pass the size information somehow to be able to use it:

void DoSomethingWithArray(int* arr, int NumOfElems)
{
    for(int i = 0; i < NumOfElems; ++i) {
        arr[i] = /*...*/
    }
}

这篇关于如何找到数组中的元素数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆