#include <iostream>
usingnamespace std;
int main() {
constchar* c = "sample text";
cout << c << endl;
char cc[] = { "sample text" };
char* pp = cc;
//I see an array indentifier is actually a pointer, too.
//so it is "char*pp=cc" here not "char*pp=&cc".
cout << pp << endl;
//why pp represents the content?
cout << *(pp) << '\n';
*pp = 'A';
cout << *(pp) << '\n';
cout << pp << endl;
int b = 8;
int* pint = &b;
cout << pint << ',' << *pint << endl;
//it' s OK that pint is the address and *pint is the value contained.
return 0;
}
The output stream gives special treatment to pointers to character types.
It inserts successive characters (till a null character is encountered) from the character array whose first element is pointed to by the pointer.
There is no such special treatment for other pointer types; it just inserts the value of the pointer.
To display the address as a pointer, cast it to const void*
To display its integer value, cast it to the unsigned integer type std::uintptr_t
(this is optional, but almost all implementations do define std::uintptr_t)
#include <iostream>
#include <cstddef>
std::ostream& dump_cstr( constchar* cstr )
{
if( cstr )
{
using vptr = constvoid* ;
using int_val = std::uintptr_t ;
return std::cout << "address: " << vptr(cstr) << " (value: " << int_val(cstr)
<< ") contents: \"" << cstr << "\"\n" ;
}
elsereturn std::cout << "nullptr\n" ;
}
#define DUMP_CSTR(cstr) ( std::cout << #cstr " " && dump_cstr(cstr) )
int main()
{
// note: the lieral arrays lit1 and lit2 may or may not be at the same address
auto& lit1 = "abcdefgh" ; DUMP_CSTR(lit1) ;
auto& lit2 = "abcdefgh" ; DUMP_CSTR(lit2) ;
// pointers ptr1 and ptr2 point to the first elements of the literal arrays
constchar* ptr1 = lit1 ; DUMP_CSTR(ptr1) ;
constchar* ptr2 = lit2 ; DUMP_CSTR(ptr2) ;
// user-defined arrays arr1 and arr2 must be at different addresses
// const; ergo one of them may have the same address as the literal array
constchar arr1[] = "abcdefgh" ; DUMP_CSTR(arr1) ;
constchar arr2[] = "abcdefgh" ; DUMP_CSTR(arr2) ;
// user-defined array arr3 must be at a different address
// non-const, ergo: it can't have the same address as the literal array
char arr3[] = "abcdefgh" ; DUMP_CSTR(arr3) ;
}