Why do I get a different value at run-time when type-casting a string to DWORD?

StackOverflow https://stackoverflow.com/questions/7476775

  •  23-01-2021
  •  | 
  •  

Вопрос

std::cout << (DWORD)"test";

If I compile and run this I get different output values each time, but I can't figure out why.

Any ideas?

PS: I'm using Windows 7 64-bit and I'm compiling with Microsoft Visual C++ 2010 Ultimate.

Это было полезно?

Решение

"test", in your code, is effectively a pointer to the start of the string. When you cast it to a DWORD, your casting the pointer to an integer type, and writing out that number.

As the memory location which is storing "test" can change with each run, the value you see will change.

Другие советы

std::cout << (DWORD)"test";

is equivalent to this:

const char *tmp = "test";
std::cout << (DWORD)tmp; 

That is, it prints the address after casting it into DWORD:

It would print the same value, if you do this also:

std::cout << (const void*)"test";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top