sizeof vs strlen in C: Key Differences

The functions sizeof and strlen serve different purposes and are used for different reasons.

  1. Sizeof is an operator, not a function, that is used to calculate the number of bytes occupied by a data type or variable in memory. It returns an integer value representing the number of bytes taken up by the data type or variable. In the C language, the sizeof operator can be used to obtain the size of arrays, structures, pointers, and other data types.

“For example,”

int a;
printf("%d\n", sizeof(a)); //输出sizeof(int)的大小

int arr[5];
printf("%d\n", sizeof(arr)); //输出数组arr的大小
  1. The function strlen is used to compute the length of a string, which is the number of characters in the string excluding the null character ‘\0’ at the end. It returns an unsigned integer value representing the length of the string.

For example:

char str[] = "Hello, World!";
printf("%d\n", strlen(str)); //输出字符串的长度

Therefore, the main difference between sizeof and strlen is:

  1. The sizeof operator is used to calculate the number of bytes occupied by a data type or variable in memory, returning an integer value.
  2. The function strlen is used to determine the length of a string, and it returns an unsigned integer value.
bannerAds