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?
Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
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 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.
You can set it to the same value, but only to 0
How to initialize all members of an array to the same value?
initialize all elements to 0
:
int myArray[10] = { 0 }; // all elements 0
There is an answer in that page for gcc as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With