【⛸️拒绝手滑,我们都是稳准狠⛸️】C++のmemset函数的小探究
👀引子
我們使用經常使用memset函數來初始化一些數據結構,常見的字符串數組、結構體、結構體數組。今天我要提出的是一個關于指針的初始化的小問題,很容易手滑寫錯了。
強調一下錯誤示例,直接用指針來memset是不對的,并不能清空指針:
void* p1 = &x;memset(p1, 0, sizeof(p1));
所以我們為了避免memset手滑導致的錯誤,經常會自己封裝一下memset函數,如“mzero(a)”宏所示,方便大家準確地使用。
使用memset函數清空指針的demo如下:
code:
output:
NULL ptr is:0 x ptr is :0x7fff671fb2d4p1 ptr is:0x7fff671fb2d4 memset p : 0x7fff671fb2d4p2 ptr is:0x7fff671fb2d4 memset &p ptr: 0p3 ptr is:0x7fff671fb2d4 mzero p: 0👃正文
其實以上問題已經轉化為memset初始化指針問題了。首先給出結論:
指針使用NULL賦值,值數據使用memset設為0。
雖然我們demo里memset方法和NULL方法從結果上看都初始化為0了,但是還是不建議使用memset來初始化指針。因為有些系統存在著“非零空指針”(某些 Honeywell-Bull 大型機使用比特模式 06000 作為 (內部的) 空指針),這時memset就不適用這種情況了。所以我們應該:
? 用空指針常量(或空指針)對指針變量初始化;
例如:int *p = NULL; int *p = 0;
? 用空指針常量(或空指針)對指針變量賦值;
例如:int i =222;int *p = &i;
👅官方文獻
追根溯源,打破沙鍋問到底。
memset
void * memset ( void * ptr, int value, size_t num );
Fill block of memory
Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
Parameters
ptr:
Pointer to the block of memory to fill.
value:
Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num:
Number of bytes to be set to the value.
size_t is an unsigned integral type.
Return Value
ptr is returned.
👂旁征博引
https://www.cplusplus.com/reference/cstring/memset/
https://www.maixj.net/ict/memset-24260
http://c-faq-chn.sourceforge.net/ccfaq/node73.html
總結
以上是生活随笔為你收集整理的【⛸️拒绝手滑,我们都是稳准狠⛸️】C++のmemset函数的小探究的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【 ➰斗艳争妍の网络协议姐妹花️➰】
- 下一篇: 2020年中国OTT大屏服务行业研究报告