查找作为 c 中函数参数接收的整数数组的大小 [英] Find the Size of integer array received as an argument to a function in c
问题描述
我想找到作为参数传递给函数的整数数组的大小.这是我的代码
void getArraySize(int arr[]){int len = (sizeof(arr)/sizeof(arr[0])printf("数组长度:%d\n",len);}int main(){int array[] = {1,2,3,4,5};getArraySize(数组);返回0;}
我收到以下警告
数组函数参数的sizeof将返回'int *' 的大小而不是 'int []' [-Wsizeof-array-argument]
请帮忙,以便我可以在function
getArraySize
中找到整数数组的长度但是我能够在 main
函数中找到 array
的大小.因为它是作为 pointer
传递的,所以我无法找到length
from with in function
.
我确实有一个想法.我可以把它放在 try/catch
块中(C
没有 try catch,只有 跳线 依赖于操作系统)并循环直到出现分段错误
.>
有没有其他方法可以用来在 function
integer array
的长度你不能那样做.当您将数组传递给函数时,它会衰减为指向第一个元素的指针,此时会丢失对其大小的了解.
如果您想知道传递给函数的数组的大小,您需要在衰变之前计算出来并将该信息与数组一起传递,例如:
void 函数 (size_t sz, int *arr) { ... }:{int x[20];函数 (sizeof(x)/sizeof(*x), x);}
i would like to find the size of integer array passed as an argument to a function. Here is my code
void getArraySize(int arr[]){
int len = (sizeof(arr)/sizeof(arr[0])
printf("Array Length:%d\n",len);
}
int main(){
int array[] = {1,2,3,4,5};
getArraySize(array);
return 0;
}
I am getting the following warning
sizeof on array function parameter will return
size of 'int *' instead of 'int []' [-Wsizeof-array-argument]
Please help so that i can find the length of integer array inside the function
getArraySize
However am able to find the size of the array
inside the main
function.Since it is passed as a pointer
, am not able to find the length
from with in the function
.
i do have an idea though.I could put this with in a try/catch
block(C
does not have try catch,Only jumpers which is OS dependent) and loop until i get a segmentation fault
.
Is there any other way i could use to find the length of integer array
inside the function
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);
}
这篇关于查找作为 c 中函数参数接收的整数数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!