12

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

Laz
  • 6,036
  • 10
  • 41
  • 54

7 Answers7

17

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 2
    This will initialize all elements to 0? Why do you say its dirty? – Laz May 23 '10 at 09:24
  • 11
    Just to clarify: It doesn't "follow suit," it *forces* them to zero. If you wrote `= { 1 };` it would put the first value as 1, and the rest would still be zeros. – Mahmoud Al-Qudsi May 23 '10 at 09:27
  • 2
    I say quick-n-dirty because, even though it is logically correct and guaranteed to work, it may confuse maintainers. I consider it a shortcut, and avoid using it unless the array or data structure is too large to conveniently initialise every element. – Marcelo Cantos May 23 '10 at 09:28
  • Good point @Computer Guru; I didn't consider the ambiguity in my statement. I've amended it. – Marcelo Cantos May 23 '10 at 09:30
  • +1 for pointing out the little-known `{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. – R.. GitHub STOP HELPING ICE Sep 20 '10 at 02:02
7

Besides the initialization syntax, you can always memset(arr, 0, sizeof(int)*10*10)

Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
5
int arr[10][10] = {0}; // only in the case of 0
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
5

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.

Thomas
  • 174,939
  • 50
  • 355
  • 478
2
int myArray[2][2] = {};

You don't need to even write the zero explicitly.

Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
1

Defining a array globally will also initialize with 0.


    #include<iostream>

    using namespace std;

    int ar[1000];
    
    int main(){


        return 0;
    }

0

int arr[10][10] = { 0 };