Memset not working

元气小坏坏 提交于 2019-12-04 06:12:28

memset works on bytes, so it fills your array of ints with 0x01010101 values (assuming int is 32 bits) which is decimal 16843009.

If you need to fill a 2-dimensional C-style array with a number:

int l[3][3];
std::fill_n(*l, sizeof l / sizeof **l, 1);

*l here decays int[3][3] into a pointer to the first element of the array (int*), sizeof l / sizeof **l yields the count of array elements.

It uses the C++ requirement that arrays be laid out contiguously in memory with no gaps, so that multi-dimensional arrays have the same layout as single-dimensional ones. E.g. int [3][3] has the same layout as int[3 * 3].

And, unlike memset, std::fill_n operates on object level, not on bytes. For built-in types the optimized version normally inlines as SIMD instructions, not less efficient than memset.

Actually, it worked very well ...

16843009 is the decimal representation of 0x01010101 (hex).

memset did its job right, i.e. it initialized every byte in the provided memory area to 0x01.

If your objective is to set each item of the array to 1 then the following will do your job,

int l[3][3] = {1,1,1,1,1,1,1,1,1};

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!