difference between sizeof and strlen in c [duplicate]
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?
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
).
sizeof
is not a method. It is a compile-time construct that determines the amount of memory a particular type or a variable occupies. strlen
, on the other hand, is a function that counts the number of consecutive non-zero char
values starting at the specified location in memory (which happens to be the same as determining the length of a zero-terminated C string).