简体   繁体   中英

How to display address of a constant character pointer

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM