Character pointers in C ++

Hi guys I have doubts about character pointers in C ++. Whenever we create a pointer to a character in C ++ char * p = "How do you do this", p must contain the address of the memory cell, which contains the value "how do you do this". However, I am puzzled by the samle code and exit. Why cout<<p return the whole string? It must indicate the value of the memory address. Secondly, why cout<<*p gives only the first character of the string? Thank you in advance! Code:

 #include <iostream> using namespace std; int main () { const char *str = "how are you\n"; int i[]={1,2,3}; cout << str << endl; // << is defined on char *. cout << i << endl; cout << *str << endl; } 

OUTPUT:

 how are you 0xbfac1eb0 h 
+4
source share
4 answers

This is due to operator overload.

the < operator is overloaded to display the string pointed to by a character pointer.

Similarly, with * p, you get the first character, so you get the first character as output.

+5
source

If you want to print the address, you must cast char* to void* , as

 const char *str = "how are you\n"; cout << (void*) str << endl; 

In the absence of translation, cout sees str as const char* (which is actually the case), and therefore cout thinks that you intend to print a string with a null char!

Think about it: if you want coud << str print the address, how would you print the string yourself?

-

In any case, this is a more detailed explanation:

operator<< overloaded for char* as well as void* :

 //first overload : free standing function basic_ostream<char, _Traits>& operator<<(basic_ostream<char, _Traits>& _Ostr, const char *_Val); //second overload : a member of basic_ostream<> _Myt& operator<<(const void *_Val); 

If there is no translation, the first overload is called first, but when you click on void* , the second overload is called!

+6
source

String C is just a bunch of bytes terminated by a null byte (this is a convention). You can also consider it as an array of bytes / characters. If you do char *str = "foobar"; , the compiler reserves some memory for these bytes, and then assigns the first byte / character to the str cell to the memory cell.

So, if you play out the str pointer, you will get a byte at that location, which will be the first character of your string. If you do *(str + 1) , you get the second, which is the same as the str[1] entry.

+1
source

cout << str << endl; prints "like you" because str is a char * , which is treated as a string.

cout << i << endl; prints 0xbfac1eb0 because i is an int [] , which is treated as int* , which is treated as void* , which is a pointer.

cout << *str << endl' prints "h" because *str is a char with a value of "h".

+1
source

Source: https://habr.com/ru/post/1343290/


All Articles