sizeof() and strlen() are two very commonly used functions in C language. They are both related to calculating memory size, but their purposes are different.

The main differences between sizeof() and strlen() are:

  • sizeof()is an operator, whilestrlen()is a function.
  • sizeof()It calculates the number of memory bytes occupied by a variable or type, whilestrlen()It calculates the number of characters in a string.
  • sizeof()It can be used for any type of data, whilestrlen()It can only be used for strings ending with the null character '\0'.
  • sizeof() calculates the length of a string, including the trailing '\0'; strlen() calculates the length of a string, excluding the trailing '\0' at the end of the string.

sizeof() is an operator rather than a function. It is used to calculate the number of memory bytes occupied by a type or a variable. It can be used to obtain the byte count of any type of data, including basic data types, arrays, structures, unions, and so on.

sizeof()

The usage of sizeof() is as follows:

sizeof(type)
sizeof(variable)
Parameter description:
  • type is a type name
  • variable is a variable name

Example

sizeof(int)  // Output 4, i.e., an integer variable occupies 4 bytes
int x;
sizeof(x)  // Output 4, i.e., the integer variable x occupies 4 bytes

sizeof() calculates the length of a string, including the trailing '\0'

Example

char s[] = "Hello, world!";
sizeof(s)  // Output 14, i.e., the string s has 14 characters (including the trailing null character '\0')

strlen()

The strlen() function is used to calculate the length of a string, i.e., the number of characters it contains (excluding the null character '\0' at the end of the string).

It should be noted that the strlen() function can only be used to calculate the length of a string ending with the null character '\0'. If the string does not contain a null character, the behavior of the strlen() function is undefined.

The usage of strlen() is as follows:

strlen(string)

Here, string is a string ending with the null character '\0', but the calculated string length does not include the trailing '\0'. For example:

Example

char s[] = "Hello, world!";
strlen(s)  // Output 13, i.e., the string s has 13 characters (excluding the trailing null character '\0')

Example

The following is a complete example of the difference between sizeof() and strlen():

Example

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void msg()
{
    char s[] = "Hello, world!";
    printf("s = %s\n", s);
    printf("sizeof(s) = %d\n", sizeof(s));
    printf("strlen(s) = %d\n", strlen(s));
}

int main(int argc, char* argv[], char* envp[])
{
    msg();
    return 0;
}

The output result is:

s = Hello, world!
sizeof(s) = 14
strlen(s) = 13