设置一个数组为一个值
问题描述:
是否有 C
更简单的方式为数组设置为比使用为
循环中去一个值通过一个设置每个值吗?
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?
答
如果你的阵列设置为全0,或者如果数组是一个字节数组,你可以使用的 memset的
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]));
如果您需要将其设置为单位0以外的东西大于一个字节(例如设置 INT
的数组s到1的),那么就没有标准功能来做到这一点 - 你必须写自己的for循环的
If you need to set it to something other than 0 in units larger than a byte (e.g. set an array of int
s to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.