Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't memset assigning 1? [duplicate]

Tags:

c++

c

memset

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

int color[1001][1001];

int main() {
    int i, j;
    memset(color, 1, sizeof(color[0][0]) * 2 * 2);
    for(i = 0; i < 4; i++) {
        for(j = 0; j < 4; j++) {
            printf("%d ", color[i][j]);
        }
        printf("\n");
    }
    printf("\n");

    return 0;
}

output:

16843009 16843009 16843009 16843009 
0 0 0 0 
0 0 0 0 
0 0 0 0 

Why isn't it assigning 1? Why didn't it print 1 instead of 16843009 ? How can i assign integer 1?

But if i write memset(color, 0, sizeof(color[0][0]) * 2 * 2); Then the output:

0 0 0 0 
0 0 0 0 
0 0 0 0 
0 0 0 0 

Why is this?

Any answer will be highly appreciated. Thanks in advance.

like image 568
shibly Avatar asked Nov 27 '22 01:11

shibly


2 Answers

Because memset sets each byte to 1.

So if int is four bytes (32 bits, what it most commonly is) then you set each element to 0x01010101.

Read more in this memset reference page.


For a more C++-ish solution I suggest using std::fill:

std::fill(&color[0][0], &color[0][0] + sizeof(color) / sizeof(color[0][0]), 1);

That will set all elements to 1.


A third option is to use std::array instead, and its fill member function:

std::array<std::array<int, 1001>, 1001> color;
...
for (auto& inner : color)
{
    inner.fill(1);
}
like image 200
Some programmer dude Avatar answered Dec 11 '22 09:12

Some programmer dude


Manpage :

#include <string.h>
void *memset(void *s, int c, size_t n)

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

Therefore, memset can't be used to initialize int array with 1 because if int is represented by 4 bytes, then it will initialize each bytes with 1.
16843009 is equivalent to 0x01010101. Each of 4 bytes are initialized with 01.
Using memset, an array of int can only be initialised with 0 or -1 because 0 and -1 both have all bits 0 and 1 respectively in two's complement binary representation regardless of the size of int data type.

like image 37
haccks Avatar answered Dec 11 '22 10:12

haccks