It's just a self-assessment question as a result of curiosity; so please cope with it.
I know that in C we pass things by value
. In case of arrays the scenario is different. We cannot pass them by their values and if we don't; a demotion from array type to pointer type will occur. We need to pass the value of the pointer to the first element of the array or pointer to the array itself. Yeah, this is what people call as array decay
. As, the original type information
of array is lost while passing we cannot obtain the size
information of the passed array in the called routine unless we pass by reference.
Have a look at the following code:
#include <stdio.h>
#include <stdlib.h>
void cal(int (*b)[3])
{
printf("%d",sizeof(*b));
}
int main()
{
int a[3] = { 2,3,4 };
cal( &a );
}
Output:
12
Okay, we got what we want. But what I concluded is that the number of elements in the array are always required when you declare a pointer to a non-variable array like this :
int a[] = { 3, 4, 5 }; // declaring an array of size 3
int (*p)[3]; // declaring a pointer to an array with length 3
p = &a ; // assignment
So, you are implicitly passing the length
of the array to called function and there always exist a different way of doing it by passing an extra length
argument to the called function in the case when you don't pass the reference of the array.
P.S. You always need to pass the length whether you do in an explicit manner or in implicit one and it is just like hardcoding things.
Is there exist an other techniques for having the size information of the passed array in the called function or I'm hitting right on the money?
And, how will you deal with the dynamic ones'?