Memset not working

2020-06-16 09:37发布

I am trying to use memset on a pure 2D Array, using the following piece of code :

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    int l[3][3];
    memset (l, 1, sizeof(l));
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << l[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

I want the whole array to be initialized by 1 using the line :

memset (l, 1, sizeof(l));

But I don't get the expected value, it gives me the following output:

16843009 16843009 16843009 
16843009 16843009 16843009 
16843009 16843009 16843009 

Thought it might be a compiler problem, so I tried using Ideone:

http://ideone.com/VFYUDg

Please help.

3条回答
Summer. ? 凉城
2楼-- · 2020-06-16 09:48

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};

查看更多
▲ chillily
3楼-- · 2020-06-16 10:03

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.

查看更多
干净又极端
4楼-- · 2020-06-16 10:04

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.

查看更多
登录 后发表回答