Using memset for integer array in C

前端 未结 10 1691
遇见更好的自我
遇见更好的自我 2020-11-27 02:20
char str[] = \"beautiful earth\";
memset(str, \'*\', 6);
printf(\"%s\", str);

Output:
******ful earth

Like the above use of memset, can we initial

10条回答
  •  [愿得一人]
    2020-11-27 03:21

    Ideally you can not use memset to set your arrary to all 1.
    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

提交回复
热议问题