Analysis of sizeof and strlen

sizeof and strlen are two different operators in C language, used to obtain the size of the object and the length of the string respectively.

sizeof operator:

  •         sizeof is an operator used to get the size of an object or data type in bytes.
  • It can be used for any data type, including basic data types (such as int, float) and custom data types (such as structures, arrays).
  •         The sizeof operator is evaluated at compile time and returns a constant expression that does not require runtime calculation.
  • For example, sizeof(int) returns the size of the integer type int, and sizeof(struct Person) returns the size of the custom structure Person.
int x = 10;
size_t size = sizeof(x); // size将包含int类型占用的字节数,通常为4(在大多数系统上)。

 

strlen function:

  • strlen is a function that gets the length of a string (excluding the null character '\0' at the end of the string).
  • It can only be used with strings, i.e. character arrays or character pointers terminated by the null character ('\0').
  • The strlen function iterates through the string at run time until a null character is encountered, then returns the number of characters.
  • For example, strlen("Hello") returns 5, and strlen(str) returns the length of the string variable str.
char str[] = "Hello, World!";
size_t length = strlen(str); // length将包含字符串的长度,不包括null字符,所以通常为12。

 

Summary:
sizeof is an operator used to get the size of an object or data type, while strlen is a function used to get the length of a string.
sizeof evaluates at compile time and returns a constant expression, while strlen calculates the length of the string at runtime.
sizeof can be used with any data type, while strlen can only be used with strings.
sizeof returns the size of the object or data type (in bytes), and strlen returns the length of the string (in characters, excluding null characters).

Guess you like

Origin blog.csdn.net/m0_73800602/article/details/131950816