No, it won't work. sizeof
a pointer returns only the size of the pointer type, not that of the array. When you pass an array as parameter to a function, the array decays into a pointer, which means that the compiler won't know anymore what exactly it points to, and if it is an array, how long it can be. The only ways for you to know it inside the function is
- pass the length as an additional parameter, or
- add an extra terminator element to the array.
Note that arrays in C and C++ don't store their size in any way, so it is the programmer who must keep it in mind and program accordingly. In the code above, you know that the actual size of a
is 5, but the compiler (and the runtime) has no way of knowing it. If you declared it as an array, i.e.
char[] word = new char [5];
the compiler would keep track of its size, and sizeof
would return this size (in bytes) while in the scope of this declaration. This allows one to apply a well known idiom to get the actual size of an array:
int size = sizeof(a) / sizeof(char);
But again, this works only as long as the compiler knows that a
is actually an array, so it is not possible inside function calls where a
is passed as a (pointer) parameter.