0

I will attach the code snippet below:

#include <bits/stdc++.h>
using namespace std;

int main()
{

    // typecasting pointers
    int x = 97;
    int *p1 = &x;
    char *p0 = (char *)p1;

    cout << *p1 << " " << *p0 << "\n";
    cout << p1 << " " << p0 << "\n";
}

The output to this code is:

97 a
0x70fe04 a

The first line is understandable. But shouldnt second line be 0x70fe04 0x70fe04 ? Why does p0 print the value at the address 0x70fe04 and not the address itself?

Expected output:

97 a
0x70fe04 0x70fe04 
  • Trivial answer: They don't because the code [didn't compile](https://godbolt.org/z/6vnxx5qo4) Hah! Forgot about the bad header. Here's what g++ has to say: https://godbolt.org/z/Y4ozaTzeG – user4581301 Jan 27 '23 at 23:29
  • 1
    `std::cout` has an overload for `const char*` (for printing null-terminated byte strings) - you should be casting to `void*` first – UnholySheep Jan 27 '23 at 23:30
  • This program has undefined behavior, as any `char*` sent to `std::cout` must be null terminated. – Drew Dormann Jan 27 '23 at 23:34
  • 1
    Looking all this over a bit more carefully, it looks like you're trying to learn C++ via competition sites. This is incredibly slow going and not particularly fruitful. Competition sites don't teach. They are where you go for practice or to show off after you've picked up a decent level of language mastery. A lot of what you'll learn is abuse of the language that you'll need to unlearn on the job, and the little details, like the one you tripped over here, are the sorts of things you would have learned from good course material and books and the competition site already expected you to know. – user4581301 Jan 27 '23 at 23:35
  • Yup, That answers the question. Thanks learnt something new -) – Sidak Bhatia Jan 27 '23 at 23:39
  • You are running this code on a machine that is storing the integer value `97` in memory as bytes `0x61 0x00 0x00 0x00`. Thus, `p0` points at the address of byte `0x61`, which is character `'a'` when interpreted as a `char` in ASCII. `operator<<` is overloaded to print a `char*` pointer as a null-terminated string. So, since `p0` is a `char*` pointer, that is why both `<< *p0` (print a single `char`) and `<< p0` (print consecutive `char`s until `0x00` is encountered) are both printing `a`. – Remy Lebeau Jan 27 '23 at 23:42
  • `cout << static_cast(p1) << " " << static_cast(p0) << "\n";` – Eljay Jan 27 '23 at 23:43
  • @Eljay there is no need to cast `p1` since it is an `int*`, so it will already call the `void*` overload of `operator<<`. Only the `char*` needs casting. – Remy Lebeau Jan 27 '23 at 23:46
  • @RemyLebeau • Just provided for consistency. And so I didn't have to re-read which one was which. – Eljay Jan 28 '23 at 02:04

0 Answers0