0

I'm trying to understand at a fundamental level what is the difference in C/C++ between a pointer to an int and a pointer to a char. Consider the following:

#include <iostream>

int main() {

    int n = 4;
    int* pn = &n;

    std::cout << pn << std::endl;

    char c = 't';
    char* pc = &c;

    std::cout << pc << std::endl;

    return 0;
}

The output is:

004FFC38
t╠╠╠╠╠╠╠╠8ⁿO

Why does the int pointer return an address as expected but the char pointer returns the actual character followed by seemingly junk values? After searching I was unable to locate a direct answer to this one.

comp1201
  • 407
  • 3
  • 13
  • 2
    The output operator `<<` have special overloads for `char*`, where the pointer is treated as a pointer to the first character of a null-terminated string. Since `pc` isn't that, you will have *undefined behavior*. – Some programmer dude Dec 05 '20 at 20:14
  • 1
    what you see is not a difference between `char*` and `int*` but a difference in the overloads for `operator<<` for those two – 463035818_is_not_an_ai Dec 05 '20 at 20:16
  • Try `<< (unsigned)pc <<...`. – i486 Dec 05 '20 at 20:17
  • @i486 Which won't work very well on e.g. 64-bit systems. Generally, when one feels the need to do a C-style cast (like `(unsigned) pc`) then that should be taken as a warning you're doing something wrong. The correct solution would be `static_cast(pc)`. – Some programmer dude Dec 05 '20 at 20:27
  • There's no fundmental difference between a pointer to an int and a pointer to a char (apart from the obvious). The difference you are seeing is **conventional**. In C a string was represented by a character pointer, and to some extent C++ continues that convention. So the program you wrote is **interpreting** the character pointer as a string. But because it isn't you get funny results. If you want to see the pointer value cast it to a void* `std::cout << (void*)pc << std::endl;` – john Dec 05 '20 at 21:22
  • `╠╠╠╠╠╠╠` is an ASCII pattern you need to learn on Visual Studio `╠` is 0xCC meaning uninitialized stack memory. – drescherjm Dec 05 '20 at 22:15
  • ***Why does the int pointer return an address as expected but the char pointer returns the actual character followed by seemingly junk values?*** Because operator<< assumes when you give it a a char* it is a c-string. – drescherjm Dec 05 '20 at 22:18
  • On the topic of 0xCC there are more magic debug codes here: [https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations](https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations) – drescherjm Dec 05 '20 at 22:21

0 Answers0