Hi folks,

Fresh newbie here. I'm taking a c++ class and I'm just a beginner. We have started to learn pointers and I discovered some puzzling behavior while messing around with the address operator & . Here is my code snippet:

char letter = 'a';
     int integer = 1;
     char letterarray[11] = "Char array";
     
     cout << letter << "\t\t" << &letter << endl;     
     cout << integer << "\t\t" << &integer << endl;
     cout << letterarray << "\t" << &letterarray << endl;

The addresses of the integer and character array output as clean hex numbers, but the char output looks strange:

a               af
1               0x22ff68
Char array      0x22ff50

In fact the garbled output of the single character address changes depending on other code around it!

If it helps I'm using Dev-C++ 4.9.9.2 on a Windows XP machine, but I also get similar weird output on the Unix system at school.

I tried searching for any explanations on Google and these forums but didn't come up with anything. If there was an obvious search I could have made to find the answer, please let me know that too for future reference.

Thank you!

It is because of default type promotion.

&integer is an (int *), which has no << overload, so it gets converted to an integer type and displayed.

Likewise, &letterarray is an (char[11] *), so it gets converted to an integer type and displayed.

However, &letter is a (char *), which does have a << overload (to print strings), so << tries to print a string. You are lucky it doesn't crash your program. You can get the correct default promotion by first casting to some pointer type that doesn't have a << overload (or at least properly prints the pointer type): cout << letter << "\t\t" << [B]static_cast<void *>([/B]&letter[B])[/B] << endl; Hope this helps.

Duoas, thank you. Yes that works. I don't know enough to understand the explanation 100%, but I'll do more research. Thanks for taking the time to reply!

Yes, you made me look it up myself. See here.

So, apparently the << operator knows how to print a (void *), which is the default promotion for most pointer types... (I think)

Hi there, I was looking for the answer to that same question! Thanks very much that was an excellent explanation!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.