指向字符数组的指针,指针的值不是地址

Pointer to array of char ,the value of the pointer is not an address?

本文关键字:指针 地址 数组 字符      更新时间:2023-10-16

这是我写的一个简单的代码。指针 p 的值是我们所知道的数组 a 的地址。
但是,为什么指针不存储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;
}

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

确实如此。

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

printf("%pn", s);

您将看到它按预期工作。

它称为运算符重载:

//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,您将看到地址。