0

这是我写的一个简单的代码。指针 p 的值是我们知道的数组 a 的地址。
但是,为什么指针s没有存储c1的地址呢?
它是如何工作的!

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;
}
4

2 回答 2

3

为什么指针s不存储c1的地址

确实如此。

您所看到的是std::ostream::operator<<具有重载的事实char*,将其视为字符串而不是指针。如果你使用

printf("%p\n", s);

你会看到它按预期工作。

于 2013-11-06T10:12:51.967 回答
1

它称为运算符重载:

//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
}

如果你将指针转换为 int 你会看到地址。

于 2013-11-06T10:30:07.910 回答