Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ char single quotes vs double quotes & memory inner workings

I want to know what the program does memory-wise during runtime as it comes across the following:

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

This produces the following:

Address: a�c�3�
Address: 0x7fff33936280

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

like image 720
nick Avatar asked Dec 15 '22 20:12

nick


1 Answers

Because &chr yields a char* (implicit addition of const here) and cout assumes that it is a string and therefore null terminated, which it is not.

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

If you want this behaviour for a const char* you will have to perform an explicit cast. The fact that there is no difference between a C-string and a pointer to a single character is one of the primary flaws of C-strings.

like image 140
Puppy Avatar answered Apr 27 '23 01:04

Puppy