简体   繁体   中英

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

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;

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;

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 int s to avoid this interaction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM