Difference Between “Size of” Operator And strlen () Function In C Language

Strlen

  1. It is a function, which is defined in a Header file named string.h
  2. It is used to get the length of an array of chars/string.
  3. It counts the numbers of characters in a string excluding null values, which means it gives you the length of null terminating string.
  4. it walks through the memory at the runtime form the character on, looking for the null values.

Size Of

  1. It is a Unary operator (compile time expression), which evaluates the amount of the memory; a variable occupies.
  2. It gives you an actual size of any type of data (allocated) in bytes (including the null values).
  3. it return the size of an operand not the string length.
  4. It doesn’t care about the values of the variable

Let us learn by an example and examine its output, when it is run on Windows System.

  1. /* strlen and sizeof with array and String */  
  2. int main(void)  
  3. {  
  4.     char msg[] =   
  5.     {  
  6.         'p',  
  7.         'r',  
  8.         'a',  
  9.         'n',  
  10.         'a',  
  11.         'y'  
  12.     };  
  13.     /* Character array */  
  14.     char name[] = "pranay"/* character array */  
  15.     char * lastname = "pranay"/* string literal */  
  16.     printf("sizeof: size of char array msg[] \"%s\" is %d bytes!\n", msg, sizeof(msg));  
  17.     printf("strlen: size of char array msg[] \"%s\" is %d bytes!\n", msg, strlen(msg));  
  18.     printf("sizeof: size of char array name1[] \"%s\" is %d bytes!\n", name1, sizeof(name));  
  19.     printf("strlen: size of char array name1[] \"%s\" is %d bytes!\n", name1, strlen(name));  
  20.     printf("sizeof: size of string \"%s\" is %d bytes!\n", name2, sizeof(lastname));  
  21.     printf("strlen: size of string \"%s\" is %d bytes!\n", name2, strlen(lastname));  
  22.     return 0;  
  23. }  
Output follows

sizeof: size of char array msg[] "pranay" is 6 bytes!
strlen: size of char array msg[] "pranay" is 6 bytes!
sizeof: size of char array name[] "pranay" is 7 bytes!
strlen: size of char array name[] "pranay" is 6 bytes!
sizeof: size of string "pranay" is 8 bytes!
strlen: size of string "pranay" is 6 bytes!

Notice, size of an operator evaluates the actual amount of memory to the array with null byte (if it’s in the list or without it, if it’s not in the list). In other words, it calculates the amount of memory in bytes, allocated to argument (argument can be of any data or type).

In case of lastname, which is pointer to a string “pranay”.
Size of the calculated actual size of the pointer, which is 8 bytes on Windows. 
Strlen() calculates the no. of characters in the string excluding (counting null bytes).