From: David Ching on
Right, I missed that he was doing that from the called function.

Thanks,
David

"Joseph M. Newcomer" <newcomer(a)flounder.com> wrote in message
news:2co2p5hujocjo2piv0nfapik0hieg3s3be(a)4ax.com...
> But consider:
>
> char addr[256];
> DoSomething(addr);
>
> void DoSomething(char * addr)
> {
> ASSERT(sizeof(addr) == 256); // FAILS
> ASSERT(sizeof(addr) == sizeof(DWORD_PTR)); // succeeds
> ASSERT(sizeof(addr) == sizeof(LPVOID)); // succeeds
> }
>
> Note that the example tries to use sizeof in the called function as if it
> had meaning to
> deliver the size of the buffer being pointed to, which, of course, it
> cannot possibly do!
>
> The only correct solution is
>
> char addr[256];
>
> DoSomething(addr, sizeof(addr));
>
> void DoSomething(char * addr, size_t len)
> {
> ...
> }
>


From: Mihai N. on
Everithing recomended in the previous posts is valid
(you need to pass the size as a parameter).

But I would recomend the discipline to use _countof
instead of sizeof.

1. sizeof gives the size in bytes, so if you move to
Unicode and char becomes wchar_t that will give the
wrong result:
TCHAR buffer[100];
sizeof(buffer) => 200

2. _countof complains at compilation if you try to
apply it on a pointer, not an array.

If _countof is not available (was added in VS 2005,
I think), you can write your own simple version
using templates, or just a macro (but then point 2
is not true anymore)

#ifndef _countof
#define _countof(a) (sizeof((a))/sizeof((a)[0]))
#endif

Mihai

--
Mihai Nita [Microsoft MVP, Visual C++]
http://www.mihai-nita.net
------------------------------------------
Replace _year_ with _ to get the real email