C语言 计算C中数组中元素的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15929869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:00:17  来源:igfitidea点击:

Count the number of elements in an array in C

carraysstatic-array

提问by Alok Save

How can I obtain the number of elements present in an integer array in C after the array is passed to a function? The following code doesn't work.

将数组传递给函数后,如何获取 C 中整数数组中存在的元素数?以下代码不起作用。

size=sizeof(array)/sizeof(array[0]);

回答by Elmar Peise

In C, you can only get the size of statically allocated arrays, i.e.

在 C 中,您只能获取静态分配数组的大小,即

int array[10];
size = sizeof(array) / sizeof(int);

would give 10.

会给 10。

If your array is declared or passed as int* array, there is no way to determine its size, given this pointer only.

如果您的数组被声明或传递为int* array,则无法确定其大小,仅给定此指针。

回答by Alok Save

You are most likely doing this inside the function to which you pass the array.
The array decays as pointer to first element So You cannot do so inside the called function.

您很可能在传递数组的函数中执行此操作。
数组衰减为指向第一个元素的指针所以你不能在被调用的函数内这样做。

Perform this calculation before calling the function and pass the size as an function argument.

在调用函数之前执行此计算并将大小作为函数参数传递。

回答by Klas Lindb?ck

You are going about it in the wrong way. I'll try to explain using a small code example. The explanation is in the code comments:

你正在以错误的方式进行。我将尝试使用一个小代码示例进行解释。解释在代码注释中:

int array[100];
int size = sizeof(array) / sizeof(array[0]);  // size = 100, but we don't know how many has been assigned a value

// When an array is passed as a parameter it is always passed as a pointer.
// it doesn't matter if the parameter is declared as an array or as a pointer.
int getArraySize(int arr[100]) {  // This is the same as int getArraySize(int *arr) { 
  return sizeof(arr) / sizeof(arr[0]);  // This will always return 1
}

As you can see from the code above you shouldn't use sizeofto find how many elements there are in an array. The correct way to do it is to have one (or two) variables to keep track of the size.

正如您从上面的代码中看到的,您不应该使用sizeof来查找数组中有多少个元素。正确的做法是使用一个(或两个)变量来跟踪大小。

const int MAXSIZE 100;
int array[MAXSIZE];
int size = 0; // In the beginning the array is empty.

addValue(array, &size, 32);   // Add the value 32 to the array

// size is now 1.

void addValue(int *arr, int *size, int value) {
    if (size < MAXSIZE) {
        arr[*size] = value;
        ++*size;
    } else {
        // Error! arr is already full!
    }
}