CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

  1. #8
    Join Date
    May 2000
    Location
    Washington DC, USA
    Posts
    715

    Re: strlen vs sizeof

    Let me try to simplify this.

    sizeof() is an operator used to determine the size of a variable. ( will never blow up ).
    strlen() is a function which counts the number of bytes in a string before the terminator '\0' character. ( will very likely blow up if your string is not null terminated. )

    thus
    Code:
    char szString[10] = "yada";            // 4 bytes + 1 terminator, in a 10 byte array
    char szZapo []     = "badabing";     // 8 bytes + 1 terminator in 9 byte array ( 8+1)
    
    printf( "sizeof( szString ) = %d\n", sizeof( szString ));  // 10 size of array
    printf( "sizeof( *szString) = %d\n", sizeof( *szString )); // 1 cause first element 'y' is a byte
    
    printf( "strlen(szString) = %d\n", strlen(szString)); // 4  number of chars before terminator
    
    printf( "sizeof( szZapo ) = %d\n", sizeof( szZapo ));  // 9 size allocated for array including terminator
    printf( "sizeof( *szZapo) = %d\n", sizeof( *szZapo )); // 1 cause first element 'b' is a byte
    
    printf( "strlen(szZapo) = %d\n", strlen(szZapo)); // 8  number of chars before terminator

    Also don't try to use sizeof(buff) > strlen(buff) to test to see if you are corrupting memory. Cause if you've corrupted memory you are hosed before this boolean test statement is true.
    Last edited by JMS; November 13th, 2007 at 02:58 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured