C++——NULL、0、nullptr


NULL在C/C++下的不同定义

在C++中,NULL就是0,定义如下

在C中,NULL就数字0

在C++中,NULL是个万能指针,可以代表指向0地址的任何数据类型

#ifndef NULL
    #ifdef __cplusplus
        #define NULL 0
    #else
        #define NULL ((void *)0)
    #endif
#endif

不过由于C++ 11逐渐普及,你应该使用nullptr代替NULL。

数字0,本身没有啥特殊意义。但是如有用在地址身上,那就会有段错误(segmentation fault)的潜在风险(如果后面你忘记对地址赋有效值)。32位x86 CPU下,从C/C++程序员角度看到的内存是2^32大小的虚拟地址空间,0地址是禁止用户代码使用的。有的操作系统可能允许你读0地址,但是写是绝对不可以的,Linux读写都不允许。一般读0地址可能如下形式,虽然使用者以及很小心,知道用const char*限制修改0地址,但是读0地址在编译器看来确是合法的,这种错误编译时期不会发现,运行时在某些操作系统下会报错。

char z = *(const char*)0;

 

_cplusplus是编译器预定于宏

//For C
gcc -dM -E - < /dev/null

//For C++
g++ -dM -E -x c++ - < /dev/null

//__cplusplus就是这么定义的
root@ubuntu:~# g++ -dM -E -x c++ - < /dev/null | grep __cplusplus
#define __cplusplus 199711L

 

snprintf

如下代码用于string与long long int之间相互转换

static inline string i64tostr(long long i64)
{
    char buf[64] = { 0 };
    snprintf(buf, sizeof(buf), "%lld", i64);
    return string(buf);
};

static inline int64_t strtoi64(const string str)
{
    return strtoll(str.c_str(), 0, 10);      //OK,三者选一个就行
    return strtoll(str.c_str(), NULL, 10);   //OK,三者选一个就行
    return strtoll(str.c_str(), nullptr, 10);//OK,三者选一个就行
}

snprintf使用

int snprintf ( char * s, size_t n, const char * format, ... );

n表示打算写入buff的最大长度

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char buffer1[100];
    int cx;
    cx = snprintf(buffer1, 100, "The half of %d is %d", 60, 60 / 2);
    if (cx >= 0 && cx < 100) {
        snprintf(buffer1 + cx, 100 - cx, ", and the half of that is %d.", 60 / 2 / 2);
    }
    puts(buffer1);//The half of 60 is 30, and the half of that is 15.

    //################################################################################

    char buffer2[16];
    size_t i;

    i = snprintf(buffer2, 5, "%s", "1234");  // 第 1 种情况
    printf("i = %d, buffer2 = %s\n", i, buffer2);    // 输出:i = 4, buffer2 = 1234

    i = snprintf(buffer2, 5, "%s", "123456");   // 第 2 种情况
    printf("i = %d, buffer2 = %s\n", i, buffer2);    // 输出:i = 6, buffer2 = 1234

    system("pause");
    return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM