Ren
Ren

Reputation: 2946

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?

Upvotes: 0

Views: 1102

Answers (2)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

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.

Upvotes: 6

xrgb
xrgb

Reputation: 271

memset will treat the passed memory as a pointer to bytes. Each byte will be set to 10, rather each int.

So you are printing out 0x0a0a0a0a, or 168430090, for each int.

Upvotes: 3

Related Questions