函数结果与非函数计算结果之间的差异

问题描述

我是C&Stack溢出的完全入门者,所以请原谅我暂时的糟糕“查询”和C编程知识。我正在尝试编写一个函数,用作计算数组中元素数量的简写。这是通过使用sizeof()函数完成的,据此,数组的大小(以字节为单位)当然要除以每个元素的字节(以字节为单位)的大小,从而计算出大小。

在主函数中,该公式按预期方式工作,即,在给出程序的原因中返回3。当在函数内计算公式并返回时,大小/结果比非函数计算的结果小1。为什么会这样呢?对于此问题的任何帮助和可能的进一步见解,将非常感谢。

unsigned int getArrayLength(float[]);

int main() {
    float arr[] = {1,2,3}; // simple arrary for demonstrational purposes
    
    printf("size of array = %d\n",getArrayLength(arr)); // this returns 2,with the compiler producing the warning "warning: 'sizeof' on array function parameter 'arr' will return size of 'float *' [-Wsizeof-array-argument]"
    printf("size of array = %d\n",(unsigned int) (sizeof(arr) / sizeof(arr[0]))); // this returns 3 which is correct
    
    return 0;
}

unsigned int getArrayLength(float arr[]) {
    return (unsigned int) (sizeof(arr) / sizeof(arr[0])); // this is producing a different & incorrect result (2,supposedly 3),as opposed to the same calculation in the main function
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)