开发者

character pointers in C++

I have a doubt regarding character pointers in c++. Whenever we create a character pointer in c++: char *p="How are you doing", p should contain the address of memory location which holds the value "how are you doing".

However, I am perplexed at a sample code and the output. Why 开发者_Python百科cout<<p gives back the entire string? It should give value of a memory address. Secondly, why does cout<<*p gives only first character of the string?

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


If you want to print the address, then you've to cast the char* to void*, as

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

In the absense of the cast, cout sees str as const char* (which in fact it is) and so cout thinks you intend to print the null-terminated char string!

Think : if you want coud << str to print the address, how would you print the string itself?

--

Anyway here is more detail explanation:

operator<< is 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);

In the absence of the cast, first overload gets called, but when you cast to void*, second overload gets called!


This is due to Operator overloading.

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

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


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

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

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


A C string is just a bunch of bytes, terminated by a null byte (that's a convention). You can also think of 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 memory location of the first byte/character to str.

So if you dereference the pointer str, you get the byte at that location which happens to be the first character of your string. If you do *(str + 1) you get the second one, which is the exact same thing as writing str[1].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜