lewicki
lewicki

Reputation: 479

C++ char array pointer confusion

I need some help understanding pointers:

Basic Pointers:

int i = 3;           
cout << i << endl;   //prints 3
cout << &i << endl;  //prints address of i

int * p = &i;
cout << p << endl;   //prints the address p points to
cout << &p << endl;  //prints the address of p
cout << *p << endl;  //prints the value stored at the address p points to

Now the confusion:

char *buf = "12345"; 
cout << &buf[2] << endl;  //prints 345
cout << buf+2 << endl;    //prints 345
cout << *buf << endl;     //prints 1
cout << *(buf+2) << endl; //prints 3
cout << buf << endl;      //prints 12345
cout << &buf << endl;     //prints 001CFA6C

How do I print the address of buf[3]?

Upvotes: 2

Views: 1678

Answers (3)

Charles Salvia
Charles Salvia

Reputation: 53289

char pointers are somewhat special in the sense that historically they have been used as strings in C. C++ is mostly backwards compatible with C, so it has support for C strings. So if you print a char pointer, rather than printing the address, it prints each character in the string until it reaches a NULL char, just like in C.

To print the actual address, cast the pointer to void*.

cout << static_cast<void*>(&buf[3]) << endl;

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

Your problem is that you try to understand pointers using char. However, char is special. In particular char const* isn't treated like any other pointer but it is treated like a C-string. That is &buf[2] is indeed the address of the third character but this address is considered to be a the start of a null-terminated sequence of characters and printing this pointer doesn't cause the pointer to be printed but rather the string starting at this address. Try the same with ints to avoid this interaction.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476990

The iostreams have a special overload for char pointers (treating them as pointers to a null-terminated array and printing the entire array). Bypass the overload by converting the pointer to a void pointer, which is printed as a numeric value:

std::cout << static_cast<void*>(buf + 3) << std::endl;

Upvotes: 1

Related Questions