2

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]?

1
  • 1
    Actually, you shouldn't use this initialization: The type of "12345" is char const[6]. To avoid backward compatibility issues it is allowed to decay this type to char*` but you loose the const. The initialization should be char const* buf = "12345";. Commented Sep 2, 2012 at 23:58

3 Answers 3

3

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;

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.