我有我的长度函数来计算数组的长度,但它给出了两个多余的垃圾数(负数)。它必须返回 6,但由于垃圾值而返回 8。
#include<stdio.h>
int length(int *arr) {
int _length = 0;
while (*arr) {
_length++;
arr++;
}
return _length;
}
int main() {
int arr[] = {2, 1, 3, 4, 5, 6};
printf("%d\n", length(arr));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您需要某种方式的终止条件。while (*arr)
假设数组以零结尾,但事实并非如此,所以你根本不能有这样的循环。
该数组的大小在编译时已知,因此无需在运行时计算任何内容。
(sizeof arr / sizeof *arr)
只要将该代码放置在与数组声明相同的范围内,即可给出数组中的项目数。
此外,sizeof
在类似函数的宏中使用该技巧(这是确定大小的惯用方法)是一种常见的解决方案:
#include <stdio.h>
#define length(arr) (sizeof(arr)/sizeof(*arr))
int main() {
int arr[] = {2, 1, 3, 4, 5, 6};
printf("%zu\n", length(arr));
return 0;
}
Run Code Online (Sandbox Code Playgroud)