0

I am not understanding the output of this ,

#include <iostream>
using namespace std; 

// pointers and arrays 
char ch1 = 'a' ,  ch2= 'b';

char ch3[6] = {'c', 'd', 'e', 'f', 'g' , 'h'};

char *ptr[3]; 

int main ()
{
    ptr[0] = &ch1 ;

    ptr[2] = ch3;
    cout << &ch1 << endl;
}   

The out put is abcdefgh .

isn't &ch1 supposed to give the address of ch1 ? I cannot make sense why the output should be abcdefgh.

  • 3
    it's called undefined behavior – ratchet freak Jun 11 '14 at 15:42
  • @ratchetfreak i cannot understand what array pointer is , its confusing . – Theorem Jun 11 '14 at 15:45
  • 1
    then don't try to understand a faulty program you won't learn anything – ratchet freak Jun 11 '14 at 15:50
  • The declaration and assignments to ptr do nothing and could be deleted without changing the behavior. – kevin cline Jun 11 '14 at 16:37
  • 1
    @kevincline Hard to say that for sure without seeing a dump of the executable. As @AustinMullins points out, one of the bytes of the address of ch1 may actually be providing the NUL that terminates the "string" (although it is possible - but not guaranteed - that ch3 would be followed by some zero bytes if ptr were not present). – Andrew Medico Jun 11 '14 at 16:47
7

The expression &ch1 does indeed produce the address of ch1. The reason you see abcdefgh printed is cout has a char* overload that prints the NUL-terminated string starting at the given address. In this case, it just so happens that ch2, ch3, and a NUL immediately follow ch1 in memory so you get abcdefgh printed.

As @rachetfreak mentions, this is undefined behavior. It is illegal to access more than one character through &ch1 because it is a pointer to a single character. On different platforms you may get different output, or a crash.

If you want to actually print the address of ch1 you can cast it to void* so that cout won't assume it's a pointer to a string:

cout << (void*)&ch1 << endl;
0

In the code shown, ch1 and ch2 are characters which are declared consecutively, and ch3 is actually an array of characters. The << operator interprets the address of ch1 as a C-style string, which is just a pointer to a null-terminated character array. So, the interesting thing to me is that storing the address of ch1 into ptr[0] results in a null character (the number 0) appearing in the byte after 'g`. As @AndrewMedico stated, this is compiler-specific behavior. I think the code was intended to show how C-strings are interpreted by IO streams, and how easy it is for bugs and security holes to creep in to otherwise good code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.