Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

dword

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.

like image 222
Purebe Avatar asked Sep 19 '11 20:09

Purebe


2 Answers

"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.

like image 193
Reed Copsey Avatar answered Nov 14 '22 23:11

Reed Copsey


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";
like image 29
Nawaz Avatar answered Nov 15 '22 01:11

Nawaz