Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate size of array which is passed to a function

Tags:

arrays

c

function

Have a look at following code

void fun( int *p )
{
    // is there any solution to calculate size of array as we are not explicitly passing its size.
}

void main ()
{
    int a[5];
    fun (a);
}

Is there any solution to calculate size of array in function or explicitly passing its size is the only solution?

like image 822
OldSchool Avatar asked Nov 17 '25 22:11

OldSchool


2 Answers

The pointer p contains no data about the size of the array. You don't quite have to pass the size as a parameter - you could end the array with a 0 like strings do, or hardcode the length, or do any of a number of other things - but without some sort of additional machinery, you can't get the length from just a pointer.

like image 74
user2357112 supports Monica Avatar answered Nov 20 '25 15:11

user2357112 supports Monica


You cannot.

It's just one pointer, which contains no size info of the array. That's why it's a common implementation to pass the size of the array as a second parameter to the function.

like image 22
herohuyongtao Avatar answered Nov 20 '25 16:11

herohuyongtao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!