0 c arrays for-loop sizeof function-definition
无法计算数组中元素的数量
#include <stdio.h>
int counter(int arr[])
{
int c =0;
for (int i = 0; arr[i] != '\0'; i++)
{
c = c + 1;
}
return c;
}
int main()
{
int a[] = { 1, 5, 3 };
int d = counter(a);
printf("%d ", d);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我如何获得 3 作为其输出吗?
您的数组需要在末尾有一个哨兵0
值(我已经选择了,但它可以是任何不被视为有效数据的东西)。
#define SENTINEL 0
int counter(int arr[])
{
int c =0;
for (int i = 0 ; arr[i] != SENTINEL; i++)
{
c = c + 1;
}
return c;
}
int main()
{
int a[] = {1, 5, 3, SENTINEL};
int d = counter(a);
printf("%d\n",d);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/TWGseeP8s