为什么指针在引用零值时为空
Why is the pointer blank when it refers to a value of zero?
在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;
&;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正在打印一个零长度的字符串。
相关文章:
- 如何使用基类指针引用派生类成员
- 将常量指针引用绑定到非常量指针
- 如果非动态变量被指针引用,何时超出范围?
- 转换指针引用的字符串
- 指针引用的生存期(以 C++为单位)
- 从 unique_ptr::get 发送指针作为指针引用进入函数
- 指针/引用的 CLion 格式
- 使用模板专用化来比较指针引用
- 如何保存指向抽象基类的指针/引用,但在 c++ 中仍然可以复制
- C++初始化指针/引用/复制细微差别
- 用数组或指针引用函数?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 强制转换为指针引用是否会导致未定义的行为
- 访问由 void 指针引用的结构的成员
- C 为什么当先前的步骤引发异常时,std :: shared_ptr的指针引用会被破坏
- 动态指针引用数组由三元运算符返回值,但有异常
- 悬空指向 int 和 char* 常量的指针/引用
- C++ 二维数组和指针引用
- 通过使用指针/引用,在C++中使用向量加快计算速度
- C++非类型模板模板到函数指针/引用