Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the address of a string

Tags:

c++

pointers

People also ask

How do I find the address of a string?

Use either: std::string::data() if your data isn't null-terminated c-string like.

How do you display address in C++?

In c++ you can get the memory address of a variable by using the & operator, like: cout << &i << endl; The output of that cout is the memory address of the first byte of the variable i we just created.

How do I print a char address?

char *st = "hello"; cout << (int)st << endl; char* str = 0; std::cout<<[b]&str[/b]<<std::endl; this displays the address of the pointer, as above in 1). If you wanted to see assigned 0, then you would display the value of the char*, as above in 2).


If you use &hello it prints the address of the pointer, not the address of the string. Cast the pointer to a void* to use the correct overload of operator<<.

std::cout << "String address = " << static_cast<void*>(hello) << std::endl;

I don't have a compiler but probably the following works:

std::cout << "Pointer address = " << (void*) hello << std::endl;

Reason: using only hello would treat is as a string (char array), by casting it to a void pointer it will be shown as hex address.


or so:

std::cout << "Pointer address = " << &hello[0] << std::endl;