memset an array to 1

后端 未结 4 1981
一生所求
一生所求 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: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 
    #include 
    #include 
    #include         //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

    Output:

    Hello, World!
    1 1 1 1 1

提交回复
热议问题