memset an array to 1

后端 未结 4 1970
一生所求
一生所求 2020-12-16 03:10

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

相关标签:
4条回答
  • 2020-12-16 03:51

    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.

    0 讨论(0)
  • 2020-12-16 03:56

    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

    0 讨论(0)
  • 2020-12-16 04:03

    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.

    0 讨论(0)
  • 2020-12-16 04:04

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题