Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between sizeof and strlen in c [duplicate]

Tags:

Possible Duplicate:
Different answers from strlen and sizeof for Pointer & Array based init of String

Can anybody help me in understanding difference between sizeof method and strlen method in c programming?

like image 304
Prabhu Avatar asked Dec 21 '11 13:12

Prabhu


People also ask

Can we use sizeof for strings?

String Length in C Using the sizeof() OperatorWe can also find the length of a string using the sizeof() Operator in C. The sizeof is a unary operator which returns the size of an entity (variable or value). The value is written with the sizeof operator which returns its size (in bytes).

What can I use instead of strlen?

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).

Does strlen count null?

The strlen() function calculates the length of a given string. The strlen() function is defined in string. h header file. It doesn't count null character '\0'.

What is the use of strlen () method in C?

The strlen() function calculates the length of a given string. The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (an unsigned integer type). It is defined in the <string.


1 Answers

strlen() is used to get the length of a string stored in an array.

sizeof() is used to get the actual size of any type of data in bytes.

Besides, sizeof() is a compile-time expression giving you the size of a type or a variable's type. It doesn't care about the value of the variable.

strlen() is a function that takes a pointer to a character, and walks the memory from this character on, looking for a null character. It counts the number of characters before it finds the null character. In other words, it gives you the length of a C-style null-terminated string.

The two are quite different. In C++, you do not need either very much, strlen() is for C-style strings, which should be replaced by C++-style std::strings, whereas the primary application for sizeof() in C is as an argument to functions like malloc(), memcpy() or memset(), all of which you shouldn't use in C++ (use new, std::copy(), and std::fill() or constructors).

like image 85
Mithun Sasidharan Avatar answered Oct 15 '22 03:10

Mithun Sasidharan