C++高级面试题:什么是 C++ 中的空指针(Null Pointer)?

发布于:2024-03-19 ⋅ 阅读:(51) ⋅ 点赞:(0)

什么是 C++ 中的空指针(Null Pointer)?

在 C++ 中,空指针(Null Pointer)是一个特殊的指针值,表示指针不指向任何有效的内存地址。空指针通常用于表示指针未初始化或指针不引用任何有效对象或函数。

C++ 中的空指针用 nullptr 关键字表示。nullptr 是 C++11 引入的空指针常量,用于明确表示空指针。

在之前的 C++ 标准中,空指针常常用 NULL 宏表示,其定义可能是 (void*)0 或者 0。但是在 C++11 引入了 nullptr 后,推荐使用 nullptr 来表示空指针,因为它是类型安全的,可以隐式转换为任意指针类型,而 NULL 宏可能存在一些类型转换和重载函数调用的问题。

以下是使用 nullptr 表示空指针的示例:

int* ptr = nullptr;  // 声明一个空指针

if (ptr == nullptr) {
    std::cout << "Pointer is nullptr" << std::endl;
} else {
    std::cout << "Pointer is not nullptr" << std::endl;
}

在这个示例中,我们声明了一个指向 int 类型的空指针 ptr,并使用 nullptr 进行初始化。然后,我们通过比较 ptr 是否等于 nullptr 来检查指针是否为空。
以下是另一个示例,演示了在函数参数中使用空指针:

#include <iostream>

// 函数接受一个整数指针作为参数
void processPointer(int* ptr) {
    if (ptr == nullptr) {
        std::cout << "Received a null pointer" << std::endl;
    } else {
        std::cout << "Received a non-null pointer" << std::endl;
    }
}

int main() {
    int* ptr1 = nullptr;
    int value = 10;
    int* ptr2 = &value;

    // 将空指针传递给函数
    processPointer(ptr1);  // 输出 "Received a null pointer"

    // 将非空指针传递给函数
    processPointer(ptr2);  // 输出 "Received a non-null pointer"

    return 0;
}

在这个示例中,我们定义了一个函数 processPointer,它接受一个整数指针作为参数。在 main 函数中,我们声明了两个指针 ptr1 和 ptr2,其中 ptr1 初始化为空指针 nullptr,而 ptr2 则指向一个整数变量 value 的地址。然后,我们分别将 ptr1 和 ptr2 传递给 processPointer 函数,观察函数对空指针和非空指针的处理。


网站公告

今日签到

点亮在社区的每一天
去签到