2013年3月11日

sizeof and strlen in C

這好像是面試時常常出現的考題呢

sizeof is an unary operator 
strlen is a function

sizeof will return the size of datatype or  the space reserved for variable in bytes
strlen will return the length of the C string excluding null byte '\0'

Here is the test program:
#include
#include  
int main(int argc, char *argv[])
{
    char a = "A";
    char *name = "Hakuma Natata";
    char bucket[20] = "1234567890";
   
    //sizeof
    printf("The sizeof char is: %u\n", sizeof(char));  //<- a="" br="" char="" nbsp="">    printf("The sizeof a is: %u\n", sizeof(a)); //<- a="" br="" char="">    printf("The sizeof *name is: %u\n", sizeof(*name)); //<- a="" br="" char="" of="" point="" pointer="" the="" value="">    printf("The sizeof name is: %u\n", sizeof(name)); //<- a="" br="" pointer="" space="">    printf("The sizeof bucket is: %u\n", sizeof(bucket)); //<- array="" assign="" br="" char="" for="" nbsp="" space="" the="">    printf("The sizeof *bucket is: %u\n", sizeof(*bucket)); //<- a="" br="" char=""> 
    //strlen
    int length = strlen(name);
    printf("The strlen name is: %d\n", length);
    length = strlen(bucket);
    printf("The strlen bucket is: %d\n", length);
    return 0;
}



沒有留言:

張貼留言