Memset not working

I am trying to use memset on a pure 2D array using the following code snippet:

#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 to 1 using a string:

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

But I do not get the expected value, it gives me the following result:

 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.

+6
source share
3 answers

memset works with bytes, so it populates your array of int values ​​0x0101010101 (assuming int is 32 bits), which is decimal 16843009.

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

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

*l here unpacks int[3][3] into a pointer to the first element of the array ( int* ), sizeof l / sizeof **l gives the number of elements in the array.

It uses the C ++ requirement that arrays be adjacent in memory without spaces, so multidimensional arrays have the same layout as unidimensional ones. For instance. int [3][3] has the same layout as int[3 * 3] .

And, unlike memset , std::fill_n works on an object level, not on bytes. For built-in types, the optimized version usually includes SIMD instructions that are no less efficient than memset .

+17
source

Actually, it worked very well ...

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

memset did its job correctly, i.e. initialized every byte in the allocated memory area to 0x01 .

+4
source

If your goal is to set each element 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,1};

-2
source

Source: https://habr.com/ru/post/957124/


All Articles