This question already has an answer here:
I have the following function in C
int func(char* param1, int param2)
//Want to calculate size of param1 array
n = sizeof(param1)/sizeof(char*);
but this doesnt give me the correct answer.
Best How To :
Note that the function prototype
int func(char* param1, int param2);
is equivalent to
int func(char **param1, int *param2);
This means the function parameters
param2 are pointers, not arrays. Pointers and arrays are different types.
sizeof(param1) / sizeof(char*);
// equivalent to
sizeof(char **) / sizeof(char *) // always 1
The above expression always evaluates to
1 because size of all pointer types is the same (except for a function pointer on which
sizeof operator may not be applied).
That's because you cannot pass an array to a function. What's actually gets passed is a pointer to the first element of the array. The pointer has no size information of the array passed to the function. Therefore, you must explicitly pass the array lengths to your function. It should have the prototype
int func(char *param1, int param2, int len_param1, int len_param2);