Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Size of integer array received as an argument to a function in c [duplicate]

Tags:

arrays

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

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

like image 886
Sunil Hari Avatar asked Sep 05 '14 06:09

Sunil Hari


People also ask

How do you determine the size of an array as a parameter?

The function clear() uses the idiom sizeof(array) / sizeof(array[0]) to determine the number of elements in the array. However, array has a pointer type because it is a parameter. As a result, sizeof(array) is equal to the sizeof(int *) .

How do you find the size of an array passed to a function as a pointer?

Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.

Can we calculate the size of the array inside the function?

Inside the function ar is a pointer so the sizeof operator will return the length of a pointer. The only way to compute it is to make ar global and or change its name. The easiest way to determine the length is size(array_name)/(size_of(int). The other thing you can do is pass this computation into the function.


2 Answers

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); } 
like image 65
paxdiablo Avatar answered Sep 18 '22 02:09

paxdiablo


The array decays to a pointer when passed.

So sizeof only works to find the length of the array if you apply it to the original array.

So you need to pass length of array as separate argument to function.

like image 38
Jayesh Bhoi Avatar answered Sep 18 '22 02:09

Jayesh Bhoi