Alex Rivera | Logout

C++ Printing value of pointer gives strange result

Asked 2011-06-22T13:51:43.413
10

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 the char array correctly.

Thanks

Edit
Report

1 Answer

4

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.

answered 2011-06-22T13:54:29.617

Your Answer