Arrays and sizeof()
I consider myself pretty savvy in C/C++ land. However, I’ve just been surprised. I just found an interesting little caveat of pointer arithmetic regarding the unary operator sizeof().
sizeof(), for those who may not be familiar with it, is a unary operator (even though it looks like a function call) that returns, creatively enough, the size of it’s operand, in bytes. On a given architecture, with a given compiler, a sizeof() on any POD type, will be constant. On my 686 with GCC 4.3.2, sizeof(char) will always return 1, because on said platform, a char always occupies exactly 1 byte of memory. sizeof(int) returns 4. sizeof(void*) returns 4. And on and on.
However, just now, I found out that if you give sizeof() an array name, the behavior is not what I expected. In the C family, array names are nothing more than constant pointers to the first element of the array. Thus, I would expect that passing a const char* (an old school string) I would get back the size of an address on my system, i.e., 4 bytes. This is simply untrue. In fact, when I used sizeof() on my null-terminated character array, it reported the string size!
Looking into the matter, I’m now told (by various manual pages and language specifications) that, when passed an array, sizeof() returns the total alloted storage for the entire array. So, a sizeof() on a string like “foobar” would return a 7. 6 bytes for the visible characters, plus 1 for the null. And this is for any array, not just an array of char.
If you didn’t know, now you do. And if you did, then forgive me as I catch up to the crowd.