开发者

C++ Printing value of pointer gives strange result

When I compile and run this C++ code, I am not getting the output I expected.

#include <iostream>
using namespace std;

int main()
{
    int * i = new int;
    long * l = new long;
    char * c = new char[100];
    float * f = new float[100];

    cout << "i " << i << endl;
    cout << "l " << l << endl;
    cout << "c " << c << endl;
    cout << "f " << f << endl;


    delete i;
    delete l;
    delete []c;
    delete []f;

    cin.get();
    return 0;
}

On a unix machine I get

i 0x967f008
l 0x967f018
c
f 0x967f090

On a windows machine the value for c prints as over a line of random characters.

Please can someone explain why it's not printing the pointer for开发者_StackOverflow中文版 the char array correctly.

Thanks


operator << for std::ostream and std::wostream is defined in special way for char pointers(char*, const char*, wchar_t* and const wchar_t* to print out a null-terminated string. This enables you to write

const char* str = "Hello, World";
std::cout << str;

and see a nice string on your stdout.

To get the pointer value, cast to void *

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


The operator<< is overloaded for char*. It will consider that you are trying to print a C-style string, and print all the chars until it finds a 0x00. Since you're not initializing the allocated memory, it will print out random garbage.


The char * is actually a C string. So I'm guessing it is trying to print it as a string.

One way to force the pointer address to be printed is to use printf:

printf("%p\n", c);


Since there is no initialization in the char's pointed by c, you dump some random memory values till it found one with value 0. It will sometimes crash, when zero is not find until your readable memory finish. Writing code like this is forbidden and wrong in Unix too, and in any other operating system.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜