21xrx.com
2024-09-20 01:15:09 Friday
登录
文章检索 我的文章 写文章
如何在 C++ 中判断空指针?
2023-07-03 21:43:35 深夜i     --     --
C++ 空指针 判断

在 C++ 中,空指针是指没有指向任何内存地址的指针。当程序试图访问空指针时,就会发生运行时错误。因此,在编写 C++ 程序时,我们需要判断指针是否为空,以避免程序崩溃。本文将介绍如何在 C++ 中判断空指针。

在 C++ 中,空指针通常用 NULL 或 nullptr 表示。以下是一个示例,展示了如何定义一个空指针,并将其和其他指针进行比较:


int *ptr = NULL; // 定义一个空指针

int *ptr2 = new int; // 定义一个非空指针

if (ptr == NULL)

  cout << "ptr is a null pointer." << endl;

if (ptr2 != NULL)

  cout << "ptr2 is not a null pointer." << endl;

在 C++11 中,新的关键字 nullptr 也可以表示空指针。使用 nullptr 可以提高代码可读性和安全性。以下是使用 nullptr 的示例代码:


int *ptr = nullptr;

int *ptr2 = new int;

if (ptr == nullptr)

  cout << "ptr is a null pointer." << endl;

if (ptr2 != nullptr)

  cout << "ptr2 is not a null pointer." << endl;

除了使用 == 或 != 运算符来判断指针是否为空之外,还可以在 if 语句中直接判断指针。以下是示例代码:


int *ptr = nullptr;

if (ptr)

  cout << "ptr is not a null pointer." << endl;

else

  cout << "ptr is a null pointer." << endl;

以上代码中,如果指针不为空,则指针被视为 true,执行第一个 cout 语句;否则,指针被视为 false,执行第二个 cout 语句。

总之,在 C++ 中,我们需要时刻注意指针的空值,避免访问空指针而导致程序的崩溃。通过使用 NULL、nullptr 或直接在 if 语句中判断指针,我们可以轻松地判断指针是否为空,从而编写更加健壮的程序。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复