Lets say I have an array like
int arr[10][10];
Now i want to initialize all elements of this array to 0. How can I do this without loops or specifying each element?
Please note that this question if for C
The most appropriate method of doing this is to use the [ Array. prototype. reduce ]( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce) function, an addition to the language in ECMAScript 5th Edition: var myArray = [1,2,3,4,5], total = myArray.
There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.
To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.
Besides the initialization syntax, you can always memset(arr, 0, sizeof(int)*10*10)
You're in luck: with 0, it's possible.
memset(arr, 0, 10 * 10 * sizeof(int));
You cannot do this with another value than 0, because memset
works on bytes, not on int
s. But an int
that's all 0
bytes will always have the value 0
.
Defining a array globally will also initialize with 0.
#include<iostream>
using namespace std;
int ar[1000];
int main(){
return 0;
}
The quick-n-dirty solution:
int arr[10][10] = { 0 };
If you initialise any element of the array, C will default-initialise any element that you don't explicitly specify. So the above code initialises the first element to zero, and C sets all the other elements to zero.
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