user968000
user968000

Reputation: 1843

memset an array to 1

I am trying to initialize a 2d array with some integer.If I initialize the array to 0 I am getting correct results but If I use some other integer I get some random values.

int main()
{
    int array[4][4];
    memset(array,1,sizeof(int)*16);
    printf("%d",array[1][2]); <---- Not set to 1
}

Upvotes: 12

Views: 18097

Answers (4)

akD
akD

Reputation: 1257

Because memset works on byte and set every byte to 1.

memset(hash, 1, cnt);

So once read, the value it will show 16843009 = 0x01010101 = 1000000010000000100000001
Not 0x00000001
But if your requiremnt is only for bool or binary value then we can set using C99 standard for C library

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>        //Use C99 standard for C language which supports bool variables

int main()
{
    int i, cnt = 5;
    bool *hash = NULL;
    hash = malloc(cnt);

    memset(hash, 1, cnt);
    printf("Hello, World!\n");

    for(i=0; i<cnt; i++)
        printf("%d ", hash[i]);

    return 0;
}

Output:

Hello, World!
1 1 1 1 1

Upvotes: 3

deau
deau

Reputation: 1223

memset allows you to fill individual bytes as memory and you are trying to set integer values (maybe 4 or more bytes.) Your approach will only work on the number 0 and -1 as these are both represented in binary as 00000000 or 11111111.

The for loop isn't too much bother:

int main() {
    int i, val = 1, max = 4;
    int array[max][max];

    max = max * max;

    for(i = 0 i < max; i++) {
       array[i] = val;
    }
}

Upvotes: 6

torek
torek

Reputation: 487725

memset works on a byte-by-byte basis only. Zeroing out the bits works in general because all integral zeros are generally all-zero-bits, so that grouping four all-zero-bit bytes into one all-zero-bits int still gives you zero. For things that are not bytes, though, the simplest way to initialize all of them is just to explicitly initialize all of them.

Upvotes: 7

ouah
ouah

Reputation: 145829

memset set every byte of your array to 1 not every int element.

Use an initializer list with all values set to 1 or a loop statement to copy a value of 1 to all the elements.

Upvotes: 16

Related Questions