1

As it can be done for integers and numerical data when a pointer is created and displayed like this

int number = 5;
int *numberaddress = &number;
cout << "The number is "<< *numberaddress << endl;
cout << "The address of number is "<< numberaddress << endl;

However when the same is done for string or constant string pointer it gives the string itself as below

char string[20] = "string";
char *stringaddress = string;
const char *stringcopy = "string";
cout << "The string is " << stringaddress << endl;
cout << "The address of string is " << *stringaddress << endl;
cout << "The stringcopy is " << stringcopy << endl;

How can I get the address of string by pointers and not just string, is there a way or there is a different method for it ?

1 Answers1

0

The output operator << treats all pointers to char as a pointer to the first character of a null-terminated string.

To print the address itself you need to cast it to void*:

cout << "The address of string is " << static_cast<void*>(stringaddress) << '\n';

Note that *stringaddress is exactly equal to stringaddress[0], which is the first character in the string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • @NumaanJaved `static_cast(stringaddress)` converts the type of `stringaddress` from `char*` to `void*`. The type `void*` is a generic pointer, it can point to anything. And more importantly, it will not be seen as a pointer to the first character of a null-terminated string. – Some programmer dude Jun 18 '20 at 09:27