C,找到一个函数内部数组长度 [英] c, finding length of array inside a function
问题描述
在数组的长度 AR
下面的程序是主正确的,但在温度
它显示的长度指针 AR
这在我的电脑上是2(以单位的sizeof(INT)
)。
In the program below the length of the array ar
is correct in main but in temp
it shows the length of the pointer to ar
which on my computer is 2 (in units of sizeof(int)
).
#include <stdio.h>
void temp(int *ar)
{
printf("%d\n", (int) sizeof(ar)/sizeof(int));
}
int main(void)
{
int ar[]={1,2,3};
printf("%d\n", (int) sizeof(ar)/sizeof(int));
temp(ar);
return 0;
}
我想知道这样数组的长度是在函数正确读,我应该如何定义的功能。谢谢你在前进
I wanted to know how I should define the function so the length of the array is read correctly in the function. Thank you in advance
推荐答案
有没有内置的方式来确定函数内部的长度。但是你通过改编
,的sizeof(ARR)
总是返回指针大小。所以最好的办法是通过元素的数量作为一个单独的参数。或者你可以像一个特殊值 0
或 1
,表示结束(喜欢它 \\ 0
的字符串,这只是的char []
)。
但是,那当然逻辑数组大小是的sizeof(ARR)/的sizeof(INT) - 1
There is no 'built-in' way to determine the length inside the function. However you pass arr
, sizeof(arr)
will always return the pointer size. So the best way is to pass the number of elements as a seperate argument. Alternatively you could have a special value like 0
or -1
that indicates the end (like it is \0
in strings, which are just char []
).
But then of course the 'logical' array size was sizeof(arr)/sizeof(int) - 1
这篇关于C,找到一个函数内部数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!