Setting whole array of chars to a value
Let's say we have:
char someArray[4];
filled with {'a','b','c','d'}
And I want to set all 4 entries to 'f' o开发者_如何学运维r any other char really.
Instead of doing individually someArray[0] = 'f'
(...) is there a way to set them all to a value?
Only because this an array of chars you can use memset
:
memset(someArray, 'f', sizeof(someArray));
If you had an array of something else (say int
) this method will not necessarily work for you as it sets the specified number of bytes (for a char array this is equivalent to the size of the array) to the 2nd parameter's value. Thus if you try to do this with an int
array and use a non-zero value memset
will not assign that non-zero value to all int
s in the array, but rather every byte for the number of bytes specified.
You can use the standard library function memset. E.g.
memset(someArray, 'f', 4);
man memset(3)
.
char someArray[4];
memset(someArray, 'f', sizeof (someArray));
精彩评论