Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize all members of an array to the same value?

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I once knew a simple way to do this. I could use memset() in my case, but isn't there a way to do this that is built right into the C syntax?

like image 389
Matt Avatar asked Oct 14 '08 13:10

Matt


People also ask

How do you make all arrays the same value?

To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.

How do you initialize an array with all elements?

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 initialize an entire array with any value in CPP?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.


1 Answers

Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.

Don't overlook the obvious solution, though:

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; 

Elements with missing values will be initialized to 0:

int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0... 

So this will initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0 

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:

int myArray[10] = {}; // all elements 0 in C++ 

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

static int myArray[10]; // all elements 0 

And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)

like image 173
aib Avatar answered Sep 21 '22 00:09

aib