Related Topics
C Programing - strlen() vs sizeof()
- Question 1
Difference between strlen() vs sizeof()
- Answer
strlen()
and sizeof()
are both commonly used functions in C and C++ programming languages, but they serve different purposes.
strlen()
is a function that takes a null-terminated string as input and returns the number of characters in the string, excluding the null terminator. It is used to find the length of a string in terms of the number of characters it contains.
Example:
char str[] = "hello world";
int len = strlen(str); // len will be 11
sizeof()
is an operator that returns the size of a data type in bytes. It can be used with any data type, including arrays and structures. It is used to find the size of a data type or variable in terms of the number of bytes it occupies in memory.
Example:
char str[] = "hello world";
int size = sizeof(str); // size will be 12 (11 characters + 1 null terminator)
Note that the sizeof()
operator returns the size of the entire array, including the null terminator for character arrays. So, in the example above, the size
variable will be 12, which is the total size of the str
array including the null terminator.