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]?
charpointers 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 acharpointer, 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;