memset 的正確用法

2022-03-30 06:04:34 字數 390 閱讀 3267

memset()位於標頭檔案string.h中,用法是將乙個位元組乙個位元組的設定為某個數.,例如:memset(a, 0, sizeof(a)), a為陣列,就是將a中的每乙個位元組都賦值為0。

以前沒有正確理解memset()的用法,將陣列賦值為1時,用memset(a, 1, sizeof(a)), 導致出現很怪的數字。

把乙個int的每個位元組都設定為1,也就是0×01010101,十進位制就是16843009

而在全部置0或者-1就沒事。這是因為:

設定為0 就是0×00000000

設定-1就是ff,所以每個位元組都置為-1就是0xffffffff,還是-1。

這也是為何可以置0和置1的原因。

如果想全部置1,只需用for即可。

linux中memset的正確用法

起因 希望對各種型別的陣列進行初始化,避免野值 函式標頭檔案 include void memset void s,int c,size t n 使用說明 the memset function fills the first nbytesof the memory area pointed to ...

linux中memset的正確用法

include the memset function fills the first n bytes of the memory area pointed to by s with the constant byte c.即對各種型別的陣列進行初始化,避免野值,注意是按位元組填充 void mem...

linux中memset的正確用法

起因 希望對各種型別的陣列進行初始化,避免野值 函式標頭檔案 include void memset void s,int c,size t n 使用說明 the memset function fills the first nbytesof the memory area pointed to ...