且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找在c中作为函数参数接收的整数数组的大小

更新时间:2023-01-14 11:58:02

您不能那样做.当您将数组传递给函数时,它会衰减为指向第一个元素的指针,这时会丢失其大小的知识.

You cannot do it that way. When you pass an array to a function, it decays into a pointer to the first element, at which point knowledge of its size is lost.

如果您想知道传递给该函数的数组的大小,则需要在 衰减之前计算出来,并将该信息与数组一起传递,例如:

If you want to know the size of an array passed to the function, you need to work it out before decay and pass that information with the array, something like:

void function (size_t sz, int *arr) { ... }
:
{
    int x[20];
    function (sizeof(x)/sizeof(*x), x);
}