无法打印char *指向0 [英] unable to print char* pointing to 0

查看:439
本文介绍了无法打印char *指向0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的comment2是完美打印。其中不打印注释,并且
程序一执行该语句就结束。
任何人都可以提供解决方案?

here the comment2 is printed perfectly. where as comment is not printed and the program ends as soon as it that statement is executed. Can anybody provide solution?

#include <iostream>
int main()
{
   const char * comment = 0;
   const char * comment2 = "hello this is not empty";
   std::cout << std::endl;
   std::cout << comment2 << std::endl;
   std::cout << "printing 0 const char *" << std::endl;
   std::cout << comment << std::endl;
   std::cout << "SUCCESSFUL" << std::endl;
}


推荐答案

std :: cout<< comment<< std :: endl;

注释为0时,故障,并且是灾难性的崩溃。

When comment is 0, we call this a segmentation fault, and is a catastrophic crash. What do you intend to happen here?

你想要 const char * comment =0; 0

您可以 const char * comment =; 表示空字符串。

do you want const char * comment = "0"; to print 0
You can do const char * comment = ""; to represent empty string.

const char * 是一个指针。当为它分配0时,它变成一个空指针,因为它现在是一个指向null的指针。当您执行cout时,库会尝试访问该位置的内存,这个过程称为取消引用指针。这会导致崩溃,如下所述。

const char * is a pointer. When 0 is assigned to it, it becomes a null pointer because it is now a pointer to null. When you perform cout, the library tries to access the memory at that location, a process called dereferencing a pointer. This causes a crash as explained below.

维基百科


在C中引用空指针会产生未定义的行为[5],这可能是灾难性的。然而,大多数实现只需停止执行所讨论的程序,通常带有分段错误。

Dereferencing a null pointer in C produces undefined behavior,[5] which could be catastrophic. However, most implementations[citation needed] simply halt execution of the program in question, usually with a segmentation fault.

这篇关于无法打印char *指向0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆