1

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.

Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • The reinterpret_cast operator produces a value of a new type that has the same bit pattern as its argument. Which compiler are you using ? g++ gives an error for the casting. – DumbCoder Jan 28 '11 at 11:21
  • @DumbCoder. When I type `char *name = "abc";`, I get the **same** output – Simplicity Jan 28 '11 at 11:23

4 Answers4

4

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;
}
Maister
  • 4,978
  • 1
  • 31
  • 34
3

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

Martin York
  • 257,169
  • 86
  • 333
  • 562
0

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.

Community
  • 1
  • 1
Clinton
  • 22,361
  • 15
  • 67
  • 163
  • The standard does say. The result should be unsurprising to somebody that understands the underlying memory architecture. [ Note: it is intended to be unsurprising to those who know the addressing structure of the underlying machine. — end note ] – Martin York Jan 28 '11 at 11:41
0

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"

canardman
  • 3,103
  • 6
  • 26
  • 28