Using memset for integer array in C

前端 未结 10 1621
遇见更好的自我
遇见更好的自我 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:15

    The third argument of memset is byte size. So you should set total byte size of arr[15]

    memset(arr, 1, sizeof(arr));
    

    However probably, you should want to set value 1 to whole elements in arr. Then you've better to set in the loop.

    for (i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) {
        arr[i] = 1;
    }
    

    Because memset() set 1 in each bytes. So it's not your expected.

    0 讨论(0)
  • 2020-11-27 03:19

    Short answer, NO.

    Long answer, memset sets bytes and works for characters because they are single bytes, but integers are not.

    0 讨论(0)
  • 2020-11-27 03:20

    No, you cannot use memset() like this. The manpage says (emphasis mine):

    The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

    Since an int is usually 4 bytes, this won't cut it.


    If you (incorrectly!!) try to do this:

    int arr[15];
    memset(arr, 1, 6*sizeof(int));    //wrong!
    

    then the first 6 ints in the array will actually be set to 0x01010101 = 16843009.

    The only time it's ever really acceptable to write over a "blob" of data with non-byte datatype(s), is memset(thing, 0, sizeof(thing)); to "zero-out" the whole struture/array. This works because NULL, 0x00000000, 0.0, are all completely zeros.


    The solution is to use a for loop and set it yourself:

    int arr[15];
    int i;
    
    for (i=0; i<6; ++i)    // Set the first 6 elements in the array
        arr[i] = 1;        // to the value 1.
    
    0 讨论(0)
  • 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 <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)
提交回复
热议问题