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

CProgrammingServer Side Programming

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\n", 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\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

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
raja
Published on 05-Nov-2018 11:13:58
Advertisements