Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c - Setting an array to one value

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...