Why does “memset(arr, -1, sizeof(arr)/sizeof(int))” not clear an integer array to -1?

前端 未结 6 1993
梦如初夏
梦如初夏 2020-11-27 12:25

Is it not possible to use memset on an array of integers? I tried the following memset call and didn\'t get the correct integer values in the

6条回答
  •  天命终不由人
    2020-11-27 13:06

    Don't use memset to initialize anything else than single-byte data types.

    At first sight, it might appear that it should work for initializing an int to 0 or -1 (and on many systems it will work), but then you're not taking into account the possibility that you might generate a trap representation, causing undefined behavior, or the fact that the integer representation is not necessarily two's complement.

    The correct way to initialize an array of int to -1, is to loop over the array, and set each value explicitly.

提交回复
热议问题