Difference between strlen() and sizeof() for string in C ?
Difference between strlen() and sizeof() for string in C ?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Puneet KankarPosted Nov 6, 2018, 3:04 AM
Sizeof operator is a compile time unary operator which can be used to compute the size of its operand.
strlen()
strlen() is a predefined function in C whose definition is contained in the header file “string.h”.
sizeof vs strlen()
Strlen on the other hand, gives you the length of a C-style NULL-terminated string.
strlen() in C-style strings can be replaced by C++ std::strings.
Madan ShekarPosted Nov 5, 2018, 6:42 AM
#include #include usingnamespacestd;intmain(){chara[] = {"Geeks for"};charb[] = {'G','e','e','k','s',' ','f','o','r'};cout <<"sizeof(a) = "<<sizeof(a);cout <<"\nstrlen(a) = "<<strlen(a);cout<<"\nsizeof(b) = "<<sizeof(b);cout<<"\nstrlen(b) = "<<strlen(b);return0;}sizeof vs strlen()
Strlen on the other hand, gives you the length of a C-style NULL-terminated string.
strlen() in C-style strings can be replaced by C++ std::strings.
sizeof() in C is as an argument to functions like malloc(), memcpy() or memset() can be replaced by C++ (use new, std::copy(), and std::fill() or constructors).
Sanwar RanwaPosted Nov 5, 2018, 5:56 AM
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 #include 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 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