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).

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.

摘自C++ reference

其实memset原本是专门给字符串赋值的, 是对内存逐字节赋值(也就是一个个的8bit char), 所以用它给int数组赋值的时候是不能赋为任意值的, 只能赋为每个字节都一样的int数字.

常用的值有下面几个:

memset(arr,0x3f3f3f3f,sizeof(arr));//1061109567, 常用inf值, 不容易溢出int范围
memset(arr,0x7f,sizeof(arr)); //2139062143, 这是用memset对int赋值所能达到的最大值
memset(arr,128,sizeof(arr)); //-2139062144, 常用-inf值
memset(arr,0x7F,sizeof(arr)); //set double to 1.38242e+306
memset(arr,0xFE,sizeof(arr)); //set double to -5.31401e+303

猜你喜欢

转载自www.cnblogs.com/cgazn/p/10940237.html