使用memset初始化数组

写在前面的ATTENTION:用memset初始化非char型(eg. int型、float型…)数组时,假如初始化值非0,可能导致错误的结果。

先举个通常用法的栗子, 将int型数组arr的元素初始化为0:

int arr[5];
memset(arr, 0, sizeof(int) * 5);

假如初始值不为0,会如何呢?例如设置为1:
使用memset(arr, 1, sizeof(int) * 5),得到的arr元素值为:0x01010101, 0x01010101, 0x01010101, 0x01010101, 0x01010101,显然并非所期望的结果。
再来回头看看memset的基础知识吧:

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.

注意到,memset填充内存时,是以byte为单位的,而上面例子中的int型数组每个元素就占了4bytes,故而填充后的值就是0x01010101了。
此外,memset的参数value,虽然是int型,但是会将其转换为unsigned char再进行填充,这样才能跟byte对应上。如果设置的value超过了unsigned char的表示范围,就溢出了,例如这样memset(arr, 256, sizeof(int) * 5),得到的结果反而与memset(arr, 0, sizeof(int) * 5)相同。
对于int型数组,假如初始化值为-1,也是可以用memset的,这种情况下得到的值是0xffffffff。但是对于其他类型例如float型数组,就不能这样做了。

BTW,如果使用int arr[5] = {1},只会将数组中的第一个元素初始化为1,其他元素则是默认值。int变量的默认值,假如是全局变量或静态局部变量则为0,假如是局部变量则为随机值(C语言规范中未作要求)。

猜你喜欢

转载自blog.csdn.net/u013213111/article/details/105328464