C ++ char single quotes and double quotes and internal memory operation

I want to know what the program uses while it is running, as it matters:

char chr = 'a'; char chrS[] = "a"; cout << "Address: " << &chr << endl; cout << "Address: " << &chrS << endl; 

This causes the following:

 Address: a c 3  Address: 0x7fff33936280 

Why can't I get the memory address "chr"?

+4
source share
2 answers

Since &chr gives char* (implicit addition of const here), and cout assumes that it is a string and therefore is null-terminated, which is not the case.

However, &chrS gives char(*)[] , which will not decay to const char* and therefore will be output via operator<<(std::ostream&, const void*) overload operator<<(std::ostream&, const void*) , which prints the address.

If you need this behavior for const char* , you will need to do an explicit cast. The fact that there is no difference between a C string and a single character pointer is one of the main drawbacks of C strings.

+12
source

Try

 cout << "Address: " << hex << (long)(&chr) << endl; 

Otherwise, when it receives a pointer to char, it thinks you are giving it a string and trying to print it as one.

0
source

All Articles