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
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 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.
= { 1 }; it would put the first value as 1, and the rest would still be zeros.{0}. It should be noted that the {0} initializer works for any type in the C language - integer types, floating point types, pointer types, array types (of any type), structures, unions, enums, you name it.Besides the initialization syntax, you can always memset(arr, 0, sizeof(int)*10*10)
memset might also be wrong for pointer or floating-point arrays.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 ints. But an int that's all 0 bytes will always have the value 0.
n*(UINT_MAX+1ULL)/255 is the family of such values (n=0,1,...,UCHAR_MAX).int myArray[2][2] = {};
You don't need to even write the zero explicitly.
Defining a array globally will also initialize with 0.
#include<iostream>
using namespace std;
int ar[1000];
int main(){
return 0;
}