strlen()
- strlen() is a predefined function in C.
- strlen() is used to get the length of an array of chars/string.
sizeof()
- sizeof is a unary operator in C.
- sizeof() is used to get the actual size of any type of data in bytes.
Some example to determine difference between strlen() and sizeof().
- sizeof() calculate the length of string including ‘\0’. Whereas strlen() calculate the length of string excluding ‘\0’.
123char arr[5] = "john";printf("%d\n", strlen(arr)); //4printf("%d\n", sizeof(arr)); //5 - .
123char arr[] = "jemjohn\0";printf("%d\n", strlen(arr)); //7printf("%d\n", sizeof(arr)); //9 - strlen() stops calculating a length of string when the pointer points to ‘\0’, even though ‘\0’ is in the string.
123char arr[]="jem\0john";printf("%d\n",strlen(arr)); //3printf("%d\n",sizeof(arr)); //9 - .
123456char arr[]="johnjohny";printf("%d\n",sizeof(&arr[1])); //8printf("%d\n",sizeof(arr)); //10printf("%d\n",strlen(&arr[1])); //8printf("%d\n",strlen(arr)); //9Here in first printf statement, the address of array elements is always an integer. So that it return value of integer data type i.e, 4 bytes in the second printf statement, it returns the number of elements in arr including ‘\0’.
strlen(&arr[1]) – This calculate length from arr[1] upto end of string excluding ‘\0’. strlen(arr) – it return the number of elements in arr excluding ‘\0’