The Wayback Machine - https://web.archive.org/web/20240116234430/https://www.geeksforgeeks.org/difference-strlen-sizeof-string-c-reviewed/
Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

sizeof()

Sizeof operator is a compile time unary operator which can be used to compute the size of its operand.

  • The result of sizeof is of unsigned integral type which is usually denoted by size_t.
  • sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union etc.

strlen()

strlen() is a predefined function in C whose definition is contained in the header file “string.h”.

  • strlen() accepts a pointer to an array as argument and walks through memory at run time from the address we give it looking for a NULL character and counts up how many memory locations it passed before it finds one.
  • The main task of strlen() is to count the length of an array or string.
    1. Type: Sizeof operator is a unary operator whereas strlen() is a predefined function in C
    2. Data types supported: Sizeof gives actual size of any type of data (allocated) in bytes (including the null values) whereas get the length of an array of chars/string.
    3. Evaluation size: 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 on the other hand, gives you the length of a C-style NULL-terminated string.
    4. Summary: The two are almost different concepts and used for different purposes.
    5. In context of C++: In C++, you do not need any of them as such. 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).
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 10 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads