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