Pointer of a character in C++

2020-04-16 04:59发布

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 int variable a too. But the first cout statement prints out an odd 'dh^#' while the second statement correctly prints a hex value ' ox23fd68'. Why is this happening?

 #include<iostream>
    using namespace std;

    int main()
    {
        char b='d';
        int a=10;
        char *c=new char[10];
        c=&b;
        int *e=&a;
        cout<<"c: "<<c<<endl;
        cout<<"e: "<<e;
    }

标签: c++
2条回答
聊天终结者
2楼-- · 2020-04-16 05:27

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<void*>(c).

My example:

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

An the output:

dÌÿÿ, 0xffffcc07

See the strange characters after 'd'.

I hope this could help a bit!

查看更多
家丑人穷心不美
3楼-- · 2020-04-16 05:33

There is a non-member overload operator<<(std::basic_ostream) for the const char* type, that doesn't write the address, but rather the (presumed) C-style string1). In your case, since you have assigned the address of a single character, there is no NUL terminator, and thus no valid C-style string. The code exhibits undefined behavior.

The behavior for int* is different, as there is no special handling for pointers to int, and the statement writes the address to the stream, as expected.

If you want to get the address of the character instead, use a static_cast:

std::cout << static_cast<void*>( c ) << std::endl;


1) A C-style string is a sequence of characters, terminated by a NUL character ('\0').

查看更多
登录 后发表回答