Question

I am new to programming and just tinkering on my own to get a better feel for concepts covered in book lessons; however, I cannot find an explanation for the following: In the code below, why are the addresses returned using (INT *), different from those using & ?

  char animal[20] = "doberman";
  const char * cat = "tiger";

  std::cout << "\nanimal: " << animal << std::endl;
  std::cout<< "cat: " << cat << std::endl;
  std::cout << "-----\n";
  std::cout << "&animal: " << &animal << std::endl;
  std::cout << "&cat: " << &cat << std::endl;
  std::cout << "(int *) cat: " << (int *) cat << std::endl;    
Was it helpful?

Solution 3

Using & means 'address of'.

Using (int *) means 'treat value as an address'.

So in this case, the (int *) treats the value "tiger" as an int pointer. *(sort of)

*It is a little more complicated. It's not exactly the value "tiger", since it is casting from a const char * rather than the string literal itself. Instead, cat is a pointer to where "tiger" is in memory, and so (int *)cat will actually be an integer pointer to where cat is in memory.

On the other hand, &cat is the address of cat - which is actually the address of the pointer to "tiger".

OTHER TIPS

The code you are showing is illegal (non portable C++).

The syntax (int *) means that the address of the string literal "tiger" is casted to a pointer to an integer but this is not allowed and it may result in undefined behavior.

You are allowed to cast any pointer type to a pointer to a char or to a pointer to unsigned char, but not the other way around.

The reason is that there are architectures in which integers and other large types MUST be at certain address (e.g. at an address that is a multiple of 4). Just creating the pointer with an invalid address is enough for undefined behavior (dereferencing is not necessary because on some CPUs even just loading an invalid address to a register used for indexing integers can raise an hardware trap).

On a PC (x86) the conversion doesn't creates problems (except may be performance problems) and simply means that the compiler will treat the memory containing "tige" as if it was an integer. Dereferencing the integer (i.e. printing *((int *)&cat)) should give 1701276020 that is

116 +           // ASCII code for 't'
105 * 256 +     // ASCII code for 'i'
103 * 65536 +   // ASCII code for 'g'
101 * 16777216  // ASCII code for 'e'

When you do &cat, where cat is a pointer, you are getting the memory location where cat itself is stored.

When you do (int*) cat, you are simply interpreting the contents of cat as an int*.

It would be highly unexpected if these two were equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top