1

I understand from here that the name of an array is the address of the first element in the array, so this makes sense to me:

int nbrs[] = {1,2};
cout << nbrs << endl;   // Outputs: 0x28ac60

However, why is the entire C-string returned here and not the address of ltrs?

char ltrs[] = "foo";
cout << ltrs << endl;   // Outputs: foo
5
  • Because it's been overloaded to print the string for convenience. Commented Aug 3, 2012 at 22:18
  • possible duplicate of C++: Making strings by pointers Commented Aug 3, 2012 at 22:20
  • A name of an array is not the address of the first item. They're very different. However, an array will sometimes pretend to be a pointer to the first item. Commented Aug 3, 2012 at 22:22
  • Also the entire C-string is being displayed, not "returned" Commented Aug 3, 2012 at 22:24
  • You're writing C++ rather than C. I would recommend you find a good C++ tutorial instead. Commented Aug 3, 2012 at 22:24

3 Answers 3

8

Because iostreams have an overload for char * that prints out what the pointer refers to, up to the first byte that contains a \0.

If you want to print out the address, cast to void * first.

Sign up to request clarification or add additional context in comments.

Comments

4

cout has operator<<() overloaded for char* arrays so that it outputs every element of the array until it reaches a null character rather than outputting the address of the pointer

Comments

2

cout, and generally, C++ streams, can handle C strings in a special way. cout operators <<, >> are overloaded to handle a number of different things, and this is one of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.