Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
指针指向零值时为什么为空? 在C++中使用指针。我遇到了意想不到的事情。我有密码: int main(){ char p=0; char* ptr=&p; cout<<"This is the pointer: "<<ptr; return 0; } intmain(){ charp=0; char*ptr=&p; cout_C++_Pointers_Char - Fatal编程技术网

指针指向零值时为什么为空? 在C++中使用指针。我遇到了意想不到的事情。我有密码: int main(){ char p=0; char* ptr=&p; cout<<"This is the pointer: "<<ptr; return 0; } intmain(){ charp=0; char*ptr=&p; cout

指针指向零值时为什么为空? 在C++中使用指针。我遇到了意想不到的事情。我有密码: int main(){ char p=0; char* ptr=&p; cout<<"This is the pointer: "<<ptr; return 0; } intmain(){ charp=0; char*ptr=&p; cout,c++,pointers,char,C++,Pointers,Char,当p未设置为0时,程序具有未定义的行为。要使其格式正确,请执行写操作 int main(){ char p=0; char* ptr=&p; cout<<"This is the character: "; // ^^^^^^^^^^^^^^ cout.write( ptr, 1 ); return 0; } intmain(){ charp=0; char*ptr=&p; cout指针指向一

p
未设置为0时,程序具有未定义的行为。要使其格式正确,请执行写操作

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

cout指针指向一个值为零的字符

指针完全有效

cout正在打印长度为零的字符串

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

char p=0;
您的变量被定义为character并分配了一个整数值零,因此在内部,您在变量p上分配了一个以null结尾的字符。 如果您更正上述声明如下,并打印更多详细信息,您可能会很清楚

char p='0'; 

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

std::coutIt不是未定义的行为,他只是在打印一个零长度的字符串。@Matteo Italia我的意思是他更改了p中的值:)也许你应该说得更清楚些(指定对于
char*
相关的
运算符,当您将其从0更改为随机指针时,我认为您可能看到堆栈中的随机数据。
cout
char*
视为以空结尾的字符串,第一个字符为p。当第一个字符为`“\0”`,它是一个空字符串。具体而言,
(char)0
(数字转换为字符,通常是其ASCII值)与
“0”
(ASCII字符零,十进制48)不同于
“0”
(包含ASCII零和空终止符的匿名字符串)。这是最清楚的答案。请注意@jmc comment to question,它最简洁地解释了为什么我看到使用问题中的原始代码打印的空字符串。
cout<<"This is the pointer: "<< ptr;
char p = 0;
char* ptr=&p;
char p=0;
char p='0'; 

std::cout<<"This is the pointer: "<<&ptr<<" ---"<<*ptr <<"----"<<ptr;