[英]Pointer to array of char ,the value of the pointer is not an address?
Here is a simple code I wrote.The pointer p 's value is the address of array a as we know. 这是我写的一个简单代码。指针p的值是我们知道的数组a的地址。
However , why does the pointer s not store the address of c1? 但是,为什么指针s不存储c1的地址?
How does it work! 它是如何工作的!
int main(int argc, const char * argv[])
{
int a[4] = {4,3,2,1};
int*p = a;
cout<<&a<<endl;//output 0x7fff5fbff8a0
cout<<p<<endl; //oupput 0x7fff5fbff8a0
char c1[4] = "abc";
char *s = c1;
cout<<&c1<<endl;//output 0x7fff5fbff894
cout<<s<<endl; //output abc
return 0;
}
why does the pointer s not store the address of c1
为什么指针s不存储c1的地址
It does. 是的
What you're seeing is that fact that std::ostream::operator<<
has an overload for char*
, treating it as a string rather than a pointer. 您所看到的事实是
std::ostream::operator<<
对char*
有重载,将其视为字符串而不是指针。 If you use 如果您使用
printf("%p\n", s);
you'll see it works as expected. 您会看到它按预期工作。
It called operator overloading: 它称为运算符重载:
//char* goes here:
std::ostream& operator<<(std::ostream &s, const char* p)
{
//print the string
}
//int* goes here:
std::ostream& operator<<(std::ostream &s, const int* p)
{
//print the address
}
if you cast the pointer to int you'll see the address. 如果将指针转换为int,您将看到地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.