I want to calculate the ‘sizeof’ array:
char* arr[] = { "abc", "def" };
When I call sizeof manually, immediately after the initialization of the array, it works fine. However if I pass the array to some function, It doesn’t give the same result.
int test(char* b[]) {
return (int)sizeof(b);
}
int _tmain(int argc, _TCHAR* argv[])
{
char* arr[] = { "abc", "def" };
int p = test(arr); // gives 4
int k = sizeof(arr); // gives 8
...
}
So what’s the problem? Sorry for the newbie question, but I really miss it.
When you use
sizeofonarrin_tmain, you’re taking the size of the array itself, which is2 * sizeof(char*) = 2 * 4 = 8on your architecture, because yourchar*s occupy32bits =4bytes.When you use
sizeofonbintest, you’re taking the size of a pointer to the first element of the array, which issizeof(char**) = 4on your architecture. The reason you’re taking the size of the pointer and not the array is that you can’t pass arrays as such to functions – instead, you pass them via a pointer to their first element. The information about the actual size of the array is thus lost in the call. Put another way, the signature of your functiontestis equivalent toint test(char **b).