C ++中的字符指针 [英] character pointers in C++
问题描述
Hi Guys
我对c ++中的字符指针有疑问。每当我们在c ++ char * p =你怎么做中创建一个字符指针时,p 应该包含内存位置的地址,它保存着你怎么样的值。 strong>
但是我对一个samle代码和输出感到困惑。为什么 cout<< p
返回整个字符串?它应该给出一个内存地址的值。第二,为什么 cout<< * p
只给出字符串的第一个字符?提前致谢!
代码:
Hi Guys
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 samle code and the output. Why 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? Thanks 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
推荐答案
这是由于操作员重载。
同样,使用* p,你将得到第一个字符,因此,您将获得第一个字符作为输出。
Similarly, with *p, you will get the first character, hence you get the first character as output.
这篇关于C ++中的字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!