【问题标题】:Why does C++ show characters when we print the pointer to a character type? [duplicate]当我们打印指向字符类型的指针时,为什么 C++ 显示字符? [复制]
【发布时间】:2014-09-12 05:16:49
【问题描述】:

考虑以下代码:

char char_a = 'A';
int int_b = 34;

char* p_a = &char_a;
int* p_b = &int_b;

cout<<"Value of int_b is (*p_b) :"<< *p_b<<endl;
cout<<"Value of &int_b is (p_b) :"<< p_b<<endl;

cout<<"Value of char_a is (*p_a) :"<< *p_a<<endl;
cout<<"Value of &char_a is (p_a) :"<< p_a<<endl;

当我运行它时,输出是:

那么为什么它在字符指针的情况下不像整数指针那样显示地址呢?

【问题讨论】:

  • 你在另一台电脑上试过这个代码吗??
  • printf("%p\n", p_a);
  • 是的,我已经检查过了。它在那里给出相同的符号。
  • 你需要cout&lt;&lt;"Value of &amp;char_a is (p_a) :"&lt;&lt; reinterpret_cast&lt;void *&gt;(p_a) &lt;&lt;endl;(你也可以使用static_cast

标签: c++ pointers


【解决方案1】:

将指针传递给字符被解释为以 NULL 结尾的 C 字符串,因为非成员 std::ostream

template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os, 
                                         const char* s );

在你的情况下,它只是一个字符,随后的内存位置是垃圾,ostream 读取内存,直到它在内存流中达到 NULL。

这绝对是一种未定义的行为,因为您将访问已分配给进程的内存之外的内存。

如果您确实需要传递字符指针并显示地址,您可以利用格式化插入器operator&lt;&lt; void *的成员重载

basic_ostream& operator<<( const void* value ); 

要访问它,您需要一个从 char *const void * 的显式指针转换

std::cout << "Value of &char_a is (p_a) :" << static_cast<const void *>(p_a) << std::endl;

【讨论】:

    【解决方案2】:

    假设你有:

    char s[] = "abcd";
    char* cp = a;
    cout << cp << endl;
    

    期望是你想看到的:

    abcd
    

    在输出中。

    std::ostream 有一个与char const* 一起使用的重载,它负责在上面的代码中打印abcd,而不仅仅是cp 的指针值。

    当你打电话时

    cout<<"Value of &char_a is (p_a) :"<< p_a<<endl;
    

    程序期望p_a 是一个以空结尾的字符串。既然不是,你看到的是垃圾。

    【讨论】:

      【解决方案3】:

      std::ostream 的运算符 char * 重载(将其作为字符串处理)。如果要打印地址,请将其转换为(void *)

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 2023-03-15
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        • 1970-01-01
        • 2020-09-09
        相关资源
        最近更新 更多