Search code examples
c++initializationmemset

Memset not working


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.


Solution

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