Pointer of a character in C++

前端 未结 2 1088
无人共我
无人共我 2021-01-22 13:29

Going by the books, the first cout line should print me the address of the location where the char variable b is stored, which seems to be the case for the

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-22 13:57

    Actually this program has problem. There is a memory leak.

    char *c=new char[10];
    c=&b;
    

    This allocates 10 characters on heap, but then the pointer to heap is overwritten with the address of the variable b.

    When a char* is written to cout with operator<< then it is considered as a null terminated C-string. As the address of b was initialized to a single character containing d op<< continues to search on the stack finding the first null character. It seems the it was found after a few characters, so dh^# is written (the d is the value of variable b the rest is just some random characters found on the stack before the 1st \0 char).

    If you want to get the address try to use static_cast(c).

    My example:

    int main() {
      char *c;
      char b = 'd';
      c = &b; 
      cout << c << ", " << static_cast(c) << endl;
    }
    

    An the output:

    dÌÿÿ, 0xffffcc07
    

    See the strange characters after 'd'.

    I hope this could help a bit!

提交回复
热议问题