Setting an array to one value

后端 未结 5 831
孤城傲影
孤城傲影 2020-12-09 17:14

Is there an easier way in C to set an array to one value than using a for loop and going setting each value one by one?

5条回答
  •  無奈伤痛
    2020-12-09 18:01

    If you're setting the array to all 0's, or if the array is an array of bytes, you can use memset

    // Set myArray to all 0's
    memset(myArray, 0, numberOfElementsInMyArray * sizeof(myArray[0]));
    

    If you need to set it to something other than 0 in units larger than a byte (e.g. set an array of ints to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.

提交回复
热议问题