Search code examples
c++memset

memset() does not work as expected


I am confused about the following code:

#include<iostream>
#include<cstring>

int main()
{
    int arr[3][4];
    memset(arr, 10, sizeof(arr));
    for(int i = 0; i < 3; ++i)
    {
        for(int j = 0; j < 4; ++j)
            std::cout<<arr[i][j]<<" ";
        std::cout<<"\n";
    }

    return 0;
}

Output:

168430090 168430090 168430090 168430090 
168430090 168430090 168430090 168430090 
168430090 168430090 168430090 168430090

I had expected running the above code would print

10 10 10 10
10 10 10 10
10 10 10 10

Can someone please explain the reason for this strange behavior?


Solution

  • Becase int is more than one bytes long. memset() fills every byte with the given value. So, every byte of your 4-byte ints contains a 10.