Search code examples
c++2dmemset

Set 2D int array elements to 1 by memset function


In c++, we usually use memset to set all elements to zero like:

int a[5][5];
memset(a,0,sizeof(a));

What if I want set all int elements to 1?

memset(a, 1, sizeof(a));

doesn't work since I cannot just set all bytes to 1.

I wonder if there is similar function as memset to set all elements(NOT JUST BYTES) to a particular value.


Solution

  • Using std::fill will work, but you have to resort to using reinterpret_cast<>, which is often considered bad form:

    #include <algorithm>
    
    int a[5][5];
    std::fill(reinterpret_cast<int*>(a),
              reinterpret_cast<int*>(a)+(5*5),
              1);
    

    Alternatively, you could take the address of the first element, which is likewise clunky:

    std::fill(&a[0][0],&a[0][0]+(5*5),1);