[基础函数]memset用法
这个基础函数,主要见过两种用法:
1.内存初始化
2.考试!!!(鉴于经常考试翻车,立个flag,逢考必对~)
memset声明:
void * memset ( void * ptr, int value, size_t num );
memset入参:
- 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.
- 由于是按照字节赋值,来看一个经典考试题:
1 #include "stdio.h" 2 #include "string.h" 3 4 int main() 5 { 6 int i = 0; 7 memset(&i, 256, sizeof(i)); 8 9 unsigned char* m = (unsigned char*)(&i); 10 for (int j = 0; j < sizeof(i); j++) 11 { 12 printf("%d\n", m[j]); 13 } 14 return 0; 15 }
output:
0
0
0
0
memset(&i, 128, sizeof(i));
output:
128
128
128
128
- 256是0x100,取一个无符号字节是0x00
- 128是0x80(0b1000 0000 或者 128),取一个无符号字节是0x80