如何指向一个字符的指针

时间:2017-10-26 13:47:20

标签: c++ pointers character

所以我想指向一个字符的指针,然后输出地址,输出这个奇怪的东西:t + a。有什么帮助吗?

#include <iostream>

using namespace std;

int main() {

char a = 't';
char* p = &a;

cout << p;

return 0;
}

3 个答案:

答案 0 :(得分:5)

您正在打印cout类型,cout << (void *)p; -- OR -- cout << static_cast<void *>(p); 尝试将其解释为字符串。

使用:

打印指针的值(它指向的地址
<af:commandButton text="NONE"
                    id="downloadInstructionsBtn"
                    action=" "
                    visible="false"
                    clientComponent="true"
                    partialSubmit="false">
       <af:fileDownloadActionListener filename="Инструкции пользователя"
       contentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                                     method="#{pageFlowScope.vocsReportsRegionController.instructionsDownload}"/> 
</af:commandButton>

答案 1 :(得分:3)

问题是char *通常不仅用作指向char的指针,而是指向null-terminated C-string的指针。 cout will then print all the characters pointed to by p until it finds a '\0',这样你就可以看到t,然后打印出无效的内存,这是一种未定义的行为,可能会崩溃或打印垃圾或其他内容。

解决此问题的方法是使用void *const void *代替,这只是一个带有地址但没有附加类型信息的指针。 void *p = &a;将是一个修复。 void *p2 = p;然后使用std::cout << p2;将是另一个。您还可以使用其他答案中显示的强制转换,但您应该使用像static_cast<const void*>(p)这样的C ++强制转换,而不是像(void *)p这样的C强制转换,因为一旦习惯了它们,它们就会变得更容易阅读和理由。

答案 2 :(得分:0)

如果您想要指针的地址,请将其转换为void指针

std::cout << (void *)p;

或使用带有%p选项的printf

printf("%p", p);

否则它将被视为空终止字符串,它不是。

相关问题