Let's say we have: char someArray[4];
filled with {'a','b','c','d'} And I want to set all 4 entries to 'f' or 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. Eg
memset(someArray, 'f', 4);
man memset(3)
.
char someArray[4];
memset(someArray, 'f', sizeof (someArray));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.