查找在c中作为函数参数接收的整数数组的大小 [英] Find the Size of integer array received as an argument to a function in c

查看:98
本文介绍了查找在c中作为函数参数接收的整数数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到作为参数传递给函数的整数数组的大小. 这是我的代码

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;
}

我收到以下警告

sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Wsizeof-array-argument]

sizeof on array function parameter will return size of 'int *' instead of 'int []' [-Wsizeof-array-argument]

请帮忙,以便我可以找到function getArraySize内整数数组的长度 但是可以在main函数中找到array的大小.由于它是作为pointer传递的,因此无法从function中的function中找到length.

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.

我确实有一个主意.我可以把它放在try/catch块中(C没有try catch,只有

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.

还有其他方法可以用来找到function

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屋!

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