Differences between strlen() and sizeof() in C++ (Random Programming Problems Part 1)
Welcome back, let’s start today with a common question: what is the differences between strlen()
and sizeof()
function in C++?
Run the code, baby, run it!
In these situation, talking around would make no sense. If you are in a hurry, I will explain it simple and easy. We need to put the code into action.
The output of the above program is:
strlen(myString) = 6
sizeof(myString) = 100
Alright, so from this, you can conclude that the strlen()
function will return the actual length of the string, and the sizeof()
function will return the actual size of the array contains the string.
I guess that is all you need to know right? Alright, then bye, have a nice day. Live long and prosper, my friend.
Explanation and details
Okay, I see that you are still here. Alright, so that’s mean you would like to know more in detail about how these things work. A man of science I see. Love to see someone who love use brain.
So let continue by quoting from the official documentation, we have these two descriptions:
strlen()
Return the length of the C string str. The length of a C string is determined by the terminating null-character.
sizeof()
Queries size of the object or type. Used when actual size of the object must be known.
char myString[100] = "Swifty";
It is important to remind you of the concept of String
in C++ here. We know, that every string terminates with a NULL character (“\0”). The strlen()
function was built to searches for that NULL character and counts the number of memory address passed. It counts the number of elements in the string till NULL. There for it will return: 6.
The sizeof()
function, however, return the number of total elements in the array, that is: 100.
That means in this situation below:
The answer will be:
strlen(myString) = 3
sizeof(myString) = 3
Because the length of the string is also the size of the array.
A bit of small talk
Okay, that’s that. Small and simple topic for the first chapter of the series. I hope the following articles will be much more informative and valuable.
Oh, I forgot. I wonder if you know who I am? Well I am just a random monkey coder. I like to write about things, have you read the first article of this series? Maybe check out Part 0. of this series?
Well I guess I keep telling myself that it doesn’t matter if there is anyone reading my blog. But maybe it matters a little bit, you know? Just a little bit. Or maybe more than that. I don’t know. But I think I’ll keep this series alive as long as I can. Because I always wanted to have a place to write things down.
Maybe I will become a famous writer one day, who knows?
Oh, and you, random stranger. Maybe you can suggest some new topic?