English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Difference between strlen() and sizeof() in C strings

strlen()

The function strlen() is a predefined function in C language. It is declared in the 'string.h' header file. It is used to get the length of an array or string.

This is the syntax of strlen() written in C language.

size_t strlen(const char *string);

Here,

string-the string to calculate its length.

This is an example of strlen() written in C language,

Example

#include <stdio.h>
#include <string.h>
int main() {
   char s1[10] = "Hello";
   int len;
   len = strlen(s1);
   printf("Length of string s1 : %d\n", len);
   return 0;
}

Output result

Length of string s1 : 10

In the above example, the char type array s1and the variable len fills s1length.

char s1[10] = "Hello";
int len;
len = strlen(s1);

sizeof()

The sizeof() function is a unary operator in C language, used to get the size of any data type (in bytes).

This is the syntax of sizeof() in C language.

sizeof(type);

Here,

type-any type, data type, or variable you want to calculate the size of.

This is an example of sizeof() in C language,

Example

#include <stdio.h>
int main() {
int a = 16;
   printf("Size of variable a: %d\n", sizeof(a));
   printf("Size of int data type: %d\n", sizeof(int));
   printf("Size of char data type: %d\n", sizeof(char));
   printf("Size of float data type: %d\n", sizeof(float));
   printf("Size of double data type: %d\n", sizeof(double));
   return 0;
}

Output result

Size of variable a: 4
Size of int data type: 4
Size of char data type: 1
Size of float data type: 4
Size of double data type: 8