memset使用注意事項

2021-08-25 15:51:20 字數 1032 閱讀 5904

linux下的原型宣告

name

memset - fill memory with a constant byte

synopsis

#include

void *memset(void *s, int c, size_t n);

description

the memset() function fills the first n bytes of the memory area

pointed to by s with the constant byte c.

return value

the memset() function returns a pointer to the memory area s.

memset 函式是記憶體賦值函式,用來給某一塊記憶體空間進行賦值的。

其原型是:void* memset(void *_dst, int _val, size_t _size);

使用時在檔案頭加上#include "stdlib.h"。

_dst是目標起始位址,_val是要賦的值,_size是要賦值的位元組數。

例1:char str[9];

我們用memset給str初始化為「00000000」,用法如下

memset(str,0,8);

注意,memset是逐字節拷貝的。

下面再看乙個例子:

例2:int num[8];

我們用memset給str初始化為,

memset(num,1,8);//這樣是不對的

乙個int是4個位元組的,8個int是32個位元組,所以首先要賦值的長度就不應該為8而是32。

因為memset是逐字節拷貝,以num為首位址的8位元組空間都被賦值為1,

即乙個int變為0x00000001 00000001 00000001 00000001,顯然,把這個數化為十進位制不會等於1的。

所以,在memset使用時要千萬小心,在給char以外的陣列賦值時,只能初始化為0或者-1。因為在計算機裡,0的二進位制都是0,-1的二進位制都是1。

memset使用注意事項

linux下的原型宣告 name memset fill memory with a constant byte synopsis include void memset void s,int c,size t n description the memset function fills the ...

C 使用memset注意事項

include void memset void dest,int ch,std size t count 它會 轉換值 ch 為 unsigned char 並複製它到 dest 所指向物件的首 count 個位元組。因此memset方法會破壞物件內部保持狀態的私有變數,從而造成未知後果。下例對s...

memset函式注意事項

memset 函式是記憶體賦值函式,用來給某一塊記憶體空間進行賦值的。其原型是 void memset void dst,int val,size t size 使用時在檔案頭加上 include stdlib.h dst是目標起始位址,val是要賦的值,size是要賦值的位元組數。例1 char ...