Laz
Laz

Reputation: 6204

How to initialize an array to something in C without a loop?

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

Upvotes: 14

Views: 10823

Answers (7)

Mehedi Hasan Shifat
Mehedi Hasan Shifat

Reputation: 720

Defining a array globally will also initialize with 0.


    #include<iostream>

    using namespace std;

    int ar[1000];
    
    int main(){


        return 0;
    }

Upvotes: 0

c4learn.com
c4learn.com

Reputation: 11

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

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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.

Upvotes: 18

Thomas
Thomas

Reputation: 181745

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.

Upvotes: 6

Terry Mahaffey
Terry Mahaffey

Reputation: 11981

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

Upvotes: 7

Khaled Alshaya
Khaled Alshaya

Reputation: 96859

int arr[10][10] = {0}; // only in the case of 0

Upvotes: 5

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29539

int myArray[2][2] = {};

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

Upvotes: 1

Related Questions