Difference between strlen() and sizeof() for string in C


strlen()

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

Here is the syntax of strlen() in C language,

size_t strlen(const char *string);

Here,

string − The string whose length is to be calculated.

Here is an example of strlen() in C language,

Example

 Live Demo

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

Output

Length of string s1 : 10

In the above example, a char type array s1 is initialized with a string and a variable len is stroing the length of s1.

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

sizeof()

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

Here is the syntax of sizeof() in C language,

sizeof( type );

Here,

type − Any type or data type or variable, you want to calculate the size of.

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

Example

 Live Demo

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

Output

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

722 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements