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