首页 > 解决方案 > 为什么获取数组长度的 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。

希望你能帮忙!提前致谢!:)

标签: c

解决方案


问题是您已将数组作为参数传递给函数。当您传递一个数组时,编译器会将其“衰减”为指向第一个元素的指针。这意味着无法从函数内部判断数组中有多少元素。

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.


推荐阅读