【问题标题】:Pointer to array of char ,the value of the pointer is not an address?指向char数组的指针,指针的值不是地址吗?
【发布时间】:2013-11-06 10:10:05
【问题描述】:

这是我写的一个简单的代码。指针 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;
}

【问题讨论】:

  • 您的代码证明,确实如此。
  • 指针s没有存储c1的地址是错误的结论。不要试图从格式化的输出中得出结论。 assert(s == &amp;c1) 是测试s 是否具有c1 地址的正确方法。您测试的是两个变量通过标准流的输出是否相同。

标签: c++ arrays pointers char


【解决方案1】:

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

确实如此。

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

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

您会看到它按预期工作。

【讨论】:

  • 在 C++ 中,您可以打印像 std::cout &lt;&lt; "pointer = " &lt;&lt; std::hex &lt;&lt; static_cast&lt;void*&gt;(somePointer) &lt;&lt; '\n'; 这样的指针
  • 是的,但是printf() 更短;-)
  • @TristanBrindle 而且更容易出错。 (虽然我也不知道它是否更短。在这两种情况下,您都必须将指针转换为void*。在printf 的情况下,不这样做是未定义的行为;在@987654328 的情况下@,你得到错误的重载如果指针类型是char*。否则,你得到一个到void*的隐式转换。在任何情况下你都不会得到未定义的行为。
  • @JoachimPileborg 你不需要std::hex,事实上,它应该被忽略,根据标准; std::hex 只影响整数类型的输出。
  • @JamesKanze 你难道没有用printf() 隐式转换到void* 吗? (不是说你错了,只是以前从未听说过它是 UB :-))
【解决方案2】:

称为运算符重载:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2017-09-03
    • 2021-01-26
    相关资源
    最近更新 更多