endl

Hi. I know <<endl flushes the buffer, and moves to the next line. what
does <<endl<<endl do when entered like this. is this why this code says
mary's name has a 33 charcater length. please compile and see.

#include <iostream>
#include <string>
using namespace std;
int main()
{
char his_name[20] = "James";
char her_name[20];

her_name[0]='M';
her_name[1]='a';
her_name[2]='r';
her_name[3]='y';

cout<<"his_name length equals "<<strlen(his_name)<<endl;
cout<<"his_name is "<<his_name<<endl;
cout<<endl<<endl;
cout<<"her_name length equals "<<strlen(her_name)<<endl;
cout<<"her_name is "<<her_name<<endl;

return 0;
}
Last edited on
what does <<endl<<endl do

The same thing as endl, twice.


strlen

The strlen function does the following: start at the memory location you pass to it, and count how many chars (i.e. how many bytes) until it reaches the values zero. It will not stop within your array. It doesn't know or care about your array. it just keeps going until it finds the first zero.

When you created the array her_name like this:
char her_name[20];
20 bytes of memory was set aside. Where in that is the first zero? Could be anywhere. It's random data.

When you did this:
1
2
3
4
her_name[0]='M';
her_name[1]='a';
her_name[2]='r';
her_name[3]='y';

you set values in the first four bytes. So where is the first zero? Could be anywhere. The remaining 16 bytes are random data.

So this:
strlen(her_name)
starts counting at the M, and then goes to the a, and then the r, and then the y, still haven't found a zero, keep going and keep counting..... and the next zero could be anywhere. Clearly, in this case, when you ran it, the first zero was 33 bytes along. This is after the end of your array, so you've been reading memory that isn't yours. This is very bad and if you go far enough, the OS will stop you with a segFault.

The moral of this story is two-fold. Firstly, understand what the functions you call do, and secondly, if you're going to use C-style strings (i.e. array of char) instead of C++ string objects, remember to put a zero at the end of the chars you care about.
Last edited on
Excellent response!!!!!!!! Thanks.
I think there's a joke somewhere about forgetting to null-terminate your C strings...
Topic archived. No new replies allowed.