简体   繁体   中英

C++ reinterpret_cast

In running this program:

#include <iostream>
int main()
{
char *name = "abc";
int i = reinterpret_cast<int>(name);
std::cout<<i<<std::endl;
return 0;
}

I got the following output:

4202656

What does this number represent? Is it a memory address? But, memory address of what? Isn't "abc" stored as an array of characters in memory?

Thanks.

It is undefined. sizeof(int) might not be equal to sizeof(char*). I'm not sure if strict aliasing rules apply here as well.

In practice however, assuming their sizes are indeed equal (most 32-bit platforms), 4202656 would represent the address of the first character in the array. I would do this more cleanly this way:

#include <iostream>
int main()
{
   const char *name = "abc"; // Notice the const. Constant string literals cannot be modified.
   std::cout << static_cast<const void*>(name) << std::endl;
}

It is probably the address of the character 'a'.
Though I don;t think this is guaranteed (ie an int may not be long enough to hold the address).

You probably want to look at the question: casting via void* instead of using reinterpret_cast

The short answer is that it could be anything at all.

This the memory address of the first character of "abc", so "a". Because an array is a pointer who point to the first value of the array.
If you do cout << *(name++) normaly "b" is printed.

So when cast name , you try to cast the adress who point to "a"

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