memset 原理

算法竞赛中经常会使用memset来给数组赋值,有时候会发现给数组赋除0、-1外的其他值,似乎会产生一些错误;

c++官网,我们可以得到memset的声明及解释;

void * memset ( void * ptr, int value, size_t num );它的作用是:Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

意思是将ptr指向的num个字节,用value来赋值,这个value被解释成unsigned char

1
2
3
4
5
6
7
8
void *(memset)(void *s, int c, size_t n)
{
const unsigned char uc = c;
unsigned char *su;
for (su = s; 0 < n; ++su, --n)
*su = uc;
return (s);
}

上面是memset的源码;比如这段程序memset(a, 1, sizeof(a));aint型数组,在源码中,将整形1赋值给无符号char,那么就会截断整型,将低位的字节0x01赋值给a的每一个字节,memseta被视为一个一个字节;因此最后得到的a中,每个int都是0x01010101;在程序中输出memset后的a中的元素,得到的值为16843009,它的十六进制也确实是0x01010101