为什么指针在引用零值时为空

Why is the pointer blank when it refers to a value of zero?

本文关键字:指针 引用 为什么      更新时间:2023-10-16

在c++中使用指针。我遇到了一些意想不到的事情。我有代码:

int main(){
  char p=0;
  char* ptr=&p;
  cout<<"This is the pointer: "<<ptr;
return 0;
}  

当我运行此代码时,ptr的输出为空。如果我将p的值更改为任何其他值,它似乎会输出一个随机指针,例如,正如我所期望的,值在运行之间发生变化。那么问题是将char值分配给0有什么不同。
额外信息:使用g++4.8.4 编译

char p=0;

您的变量被定义为字符,并分配了一个整数值零,因此在内部您将在变量p上分配一个以null结尾的字符。如果您按照以下方式更正上述声明并打印更多详细信息,您可能会明白。

char p='0'; 
std::cout<<"This is the pointer: "<<&ptr<<" ---"<<*ptr <<"----"<<ptr;

&amp;ptr->获取ptr 的地址

*ptr->获取分配给ptr 的值

ptr->从ptr获取字符串,直到它看到一个null终止字符,因此期望垃圾值作为输出。

演示:http://coliru.stacked-crooked.com/a/2d134412490ca59a

char p = 0;
char* ptr=&p;

这里ptr是一个零长度字符串的指针。因为它是一个指向zore(\0(的char*指针,zore被认为是字符串的末尾。

p未设置为0时,程序具有未定义的行为。要使其形成良好的写入

int main(){
  char p=0;
  char* ptr=&p;
  cout<<"This is the character: ";
  //             ^^^^^^^^^^^^^^                 
  cout.write( ptr, 1 );
return 0;
}  

int main(){
  char p=0;
  char* ptr=&p;
  cout<<"This is the pointer: "<<( const void * )ptr;
return 0;
}  

否则,此语句

  cout<<"This is the pointer: "<< ptr;

只在p设置为0时输出一个空字符串。在其他情况下,它会在字符p之后输出一些垃圾,直到遇到零字符。

另一种方法可能看起来像

int main(){
  char p[2]= { 0 };
  char* ptr=&p;
  cout<<"This is the pointer: "<< ptr;
return 0;
}  

此声明

cout<<"This is the pointer: "<< ptr;

输出ptr指向的字符串。字符串是以零字符结尾的一系列字符。因此,您应该定义一个至少包含两个字符的字符数组,其中第二个字符将始终设置为0。

您的指针指向的是一个值为零的字符。

指针完全有效。

cout正在打印一个零长度的字符串。