Using memset for integer array in C

前端 未结 10 1731
遇见更好的自我
遇见更好的自我 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条回答
  •  猫巷女王i
    2020-11-27 02:58

    No, you can't [portably] use memset for that purpose, unless the desired target value is 0. memset treats the target memory region as an array of bytes, not an array of ints.

    A fairly popular hack for filling a memory region with a repetitive pattern is actually based on memcpy. It critically relies on the expectation that memcpy copies data in forward direction

    int arr[15];
    
    arr[0] = 1;
    memcpy(&arr[1], &arr[0], sizeof arr - sizeof *arr);
    

    This is, of course, a pretty ugly hack, since the behavior of standard memcpy is undefined when the source and destination memory regions overlap. You can write your own version of memcpy though, making sure it copies data in forward direction, and use in the above fashion. But it is not really worth it. Just use a simple cycle to set the elements of your array to the desired value.

提交回复
热议问题