Search code examples
c++cmemset

Why isn't memset assigning 1?


#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.


Solution

  • 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.