c - 为什么获取数组长度的 sizeof 函数在我的函数中不起作用?
问题描述
新来的 :)
double average(int arr[]) {
int total = 0;
int i;
int count = 0;
double avg;
int len = sizeof arr / sizeof arr[0];
printf("%i\n", len);
for (i=0; i<len; i++)
{
total += arr[i];
count += 1;
}
avg = (double) total / count ;
return avg; }
int main() {
int array1[5] = {150, 20, 20, 40, 190};
printf("%f", average(array1));
函数 average(int arr[]) 旨在找到数组中所有元素的平均值,然后在下面的主函数中调用
只是想问为什么 sizeof array1 / sizeof array1[0] 没有返回我给定数组的正确长度(在这种情况下 = 5)。它反而返回 2。
希望你能帮忙!提前致谢!:)
解决方案
问题是您已将数组作为参数传递给函数。当您传递一个数组时,编译器会将其“衰减”为指向第一个元素的指针。这意味着无法从函数内部判断数组中有多少元素。
The expression that you're using to calculate the array size is, then, dividing the size of a pointer by the size of an integer. The result is two because, on many modern platforms, integers are 32 bit and pointers are 64 bit.
推荐阅读
- firebase - 数组 usersubids 中只有一项被渲染到显示器
- angular - 有没有办法在 HTML 中动态注入管道?角 9
- android - 如何在不影响 Android Studio 中最低 API 级别的情况下调整边到边屏幕
- java - 如何为对象(minIO)设置生命周期规则?
- snowflake-cloud-data-platform - 从雪花发送电子邮件警报
- vue.js - 将 Vuetify 添加到单个 .vue 组件
- javascript - 单击按钮时Divs不在正确的位置
- json - SQLite 中的 JSON 函数
- mongodb - Mongoose 从数组中返回一个对象
- python - 是否可以在不首先使用 GitPython(或更一般的 Git)克隆存储库的情况下检索当前 HEAD 的提交 ID?