Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 597
Laz Avatar asked May 23 '10 09:05

Laz


People also ask

How do you add an element to an array without loop?

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.

What are the two ways to initialize an array in C?

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.

How do you manually initialize an array?

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.


4 Answers

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

like image 174
Terry Mahaffey Avatar answered Oct 24 '22 20:10

Terry Mahaffey


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.

like image 24
Thomas Avatar answered Oct 24 '22 20:10

Thomas


Defining a array globally will also initialize with 0.


    #include<iostream>

    using namespace std;

    int ar[1000];
    
    int main(){


        return 0;
    }

like image 44
ShifaT Avatar answered Oct 24 '22 20:10

ShifaT


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.

like image 45
Marcelo Cantos Avatar answered Oct 24 '22 20:10

Marcelo Cantos