sizeof............

Harold Bamford wrote:
And you are correct about VC++ doing the right thing with sizeof as opposed to strlen().
Didn't use to be like that years ago. I've been burned too many times by doing a sizeof on a constant character string which always returned a size of the pointer that I never do it anymore.


   Are you sure you were using sizeof(...) correctly?  sizeof(...) is a compile-time operator and as such can only determine the size of variables that are known at that point in compilation.  For example:

char    caArray[ 32 ];

strcpy( caArray, "Hi!" );
TRACE( "sizeof: %d/n", sizeof( caArray ) );    // Returns "32"
TRACE( "strlen: %d/n", strlen( caArray ) );    // Returns "3"


   In the above code, sizeof(...) works correctly because caArray is of a size known at the point where sizeof(...) is encountered; it is created and referenced in the same (or nested) scope.  However, if you pass caArray to a function (creating a brand new scope), it degrades to a normal pointer, and sizeof(...) will return the size of a pointer, because at compile-time, it has no idea what will be passed for that parameter.  For example:

int    GetSize( char caArray[] )   { return( sizeof( caArray ) ); };
//
// ...
//
char    caArray[ 32 ];

strcpy( caArray, "Hi!" );
TRACE( "sizeof: %d/n", sizeof( caArray ) );    // Returns "32"
TRACE( "strlen: %d/n", strlen( caArray ) );    // Returns "3"
TRACE( "GetSize: %d/n", GetSize( caArray ) );  // Returns "4"


   Note that even though I put char caArray[] as the parameter to the function, it still becomes a pointer-to-char.  Also, if you compile this code on Warning Level 4, you will get a warning about caArray being an "unreferenced parameter".  Why?  Because sizeof(...) is a compile-time operator, so it resolves to a constant value of 4, technically leaving caArray out of the picture.

   The reason sizeof("ms-help://") works is because is size is known (note that it includes the terminating NUL character).  But as with the stack-allocated array above, once you pass it to a function, it degrades from a "constant array" into a plain old pointer.

   Peace!

-=- James
If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
Tip for new SUV drivers: Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
DeleteFXPFiles & CheckFavorites
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章