Sizeof is a compilation-time operator used to calculate the memory size of variables, data types, arrays, etc., typically in bytes. The return value of sizeof is a constant determined at compile time and does not change with the content of the variable. For example:
cint a; printf("%zu", sizeof(a)); // On most platforms, the output will be 4, as int typically occupies 4 bytes.
sizeof does not require the variable to be initialized. When applied to arrays, sizeof computes the size of the entire array. For example:
cint arr[10]; printf("%zu", sizeof(arr)); // The output will be 40 on a system where each int is 4 bytes.
Strlen is a runtime function used to calculate the length of a C-style string (a character array terminated by a null character '\0'), excluding the terminating null character. It calculates the string length by traversing the string until it finds the first null character. For example:
cchar str[] = "hello"; printf("%zu", strlen(str)); // The output will be 5
In this example, although the array str is allocated 6 bytes (including the trailing '\0'), strlen only counts the characters before the first '\0'.
Applicable Scenarios and Notes
- Sizeof is very useful for determining the size of any type or data structure in memory, especially during memory allocation, array initialization, etc.
- Strlen is suitable for scenarios where you need to calculate the actual number of characters used in a string, such as string processing or calculating the length before sending a string to the network.
A Specific Application Example
Suppose you are writing a function that needs to create a copy of a user-input string. Using sizeof may not be appropriate, as it returns the size of the entire array, not the actual length of the string. Here, you should use strlen to obtain the actual length of the input string and then allocate memory:
cchar *duplicate_string(const char *src) { size_t len = strlen(src); char *dest = malloc(len + 1); // +1 for the trailing null character if (dest) { strcpy(dest, src); } return dest; }
In this example, using strlen ensures that only the necessary memory is allocated, avoiding waste. It also guarantees that the copied string is correct and complete, including the trailing null character.