Question: why is the pointer value ( pChar = muэ ), the pointer is the same type, and here there are some letters. Help figure out why this behavior.

Code:

 //4. указатель на указатель на char typedef char * myPointerChar; typedef myPointerChar * myPointerPointerChar; //char** int main() { myPointerChar pChar = /*&ch3*/ new char('m'); myPointerPointerChar ppChar = &pChar; std::cout << "myPointerChar pChar = " << pChar << " ;*myPointerChar *pChar = " << *pChar << "\n"; std::cout << "myPointerPointerChar ppChar = " << ppChar << " ;*myPointerPointerChar *ppChar = " << *ppChar << " ;**myPointerPointerChar **ppChar = " << **ppChar << "\n"; return 0; } 

Displayed value:

 myPointerChar pChar = muэ ;*myPointerChar *pChar = m myPointerPointerChar ppChar = 0x61fe7c ;*myPointerPointerChar *ppChar = muэ ;**myPointerPointerChar **ppChar = m 

Question: why is the pointer value ( pChar = muэ ), the pointer is the same type, and here there are some letters. Help figure out why this behavior.

  • This behavior in IDE 2: in QtCreator and VisualStudio 2017 - Sakton
  • The std :: hex manipulator does not change the situation ... - Sakton

1 answer 1

Everything is bytes and nothing but bytes. Then the interpretation of bytes begins: into an integer, into a string, into executable code, into bytecode, and so on.

The operator new (), to put it bluntly, allocates memory and returns, for example, 4 bytes, which contain the address of this memory. If they are interpreted as a number, there will be, for example, 0x30303030. And if these same bytes are interpreted as a string - "0000".

You have allocated a single byte memory. At output from the pointer, the address of this allocated memory is taken and a string is output from there. It is expected that the string is terminated by zero, but obviously you do not write this zero anywhere in memory, so two characters with garbage are output.

  • that is, how it is not initialized: pChar - gets the address in the heap char ('m'); ppChar - get pointer address - pChar; Or do I have an eclipse in my head? The type is known to the compiler - a pointer, and once a pointer, then the representation must be appropriate. - Sakton
  • @sakton not, this is my eclipse :-) There is no terminating zero, so two garbage symbols appear. - Vladimir Martyanov
  • if I add the term zero, then the char [] line will already be there, I don’t ask for the line, but I’m asking for the pointer address - Sakton
  • printf ("0x% X \ n", pChar) try. - Vladimir Martyanov
  • I suspect overloading the operator "<<" and, as a result, different behavior for different data types. - Vladimir Martyanov