在作为参数传递的数组上使用 sizeof [英] Using sizeof on arrays passed as parameters

查看:20
本文介绍了在作为参数传递的数组上使用 sizeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
作为参数传递的数组大小

鉴于下面的函数,我理解 sizeof 返回数组中该类型的指针的大小.

Given the function below I understand that sizeof returns the size of the pointer of the type in the array.

int myFunc(char my_array[5])
{
    return sizeof(my_array);
}

但是,对未作为参数传递的数组调用 sizeof 通常会返回数组的大小.

However calling sizeof on an array not passed as a parameter normally returns the sizeof the array.

是什么导致了这种不一致?当数组作为参数传递时,获取数组大小的最佳方法是什么?

What causes this inconsistency? What is the best way of getting the size of an array when it is passed as a parameter?

推荐答案

造成这种不一致的原因是什么?

数组的名称作为指向其第一个元素的指针衰减.
当您将数组传递给函数时,会发生这种衰减,因此传递给 sizeof 的表达式是一个指针,从而返回指针大小.

The name of the array decays as an pointer to its first element.
When you pass an array to an function, this decaying takes place and hence the expression passed to sizeof is a pointer thus returning pointer size.

然而,传递给 sizeof 的数组总是返回数组的大小,因为在这种情况下没有衰减到指针.

However, an array passed to sizeof always returns size of the array because there is no decaying to an pointer in this case.

当数组作为参数传递时,获取数组大小的最佳方法是什么?

不要按值传递,而是按引用传递或
将大小作为单独的参数传递给函数.

Don't pass them by value, pass them by reference or
Pass size as an separate argument to the function.

这篇关于在作为参数传递的数组上使用 sizeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆