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?

Solutions

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.)

If your compiler is GCC you can use following syntax:

int array[1024] = {[0 ... 1023] = 5};

Check out detailed description: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html

For statically initializing a large array with the same value, without multiple copy-paste, you can use macros:

#define VAL_1X     42
#define VAL_2X     VAL_1X,  VAL_1X
#define VAL_4X     VAL_2X,  VAL_2X
#define VAL_8X     VAL_4X,  VAL_4X
#define VAL_16X    VAL_8X,  VAL_8X
#define VAL_32X    VAL_16X, VAL_16X
#define VAL_64X    VAL_32X, VAL_32X

int myArray[53] = { VAL_32X, VAL_16X, VAL_4X, VAL_1X };

If you need to change the value, you have to do the replacement at only one place.

Edit: possible useful extensions

(courtesy of Jonathan Leffler)

You can easily generalize this with:

#define VAL_1(X) X
#define VAL_2(X) VAL_1(X), VAL_1(X)
/* etc. */

A variant can be created using:

#define STRUCTVAL_1(...) { __VA_ARGS__ }
#define STRUCTVAL_2(...) STRUCTVAL_1(__VA_ARGS__), STRUCTVAL_1(__VA_ARGS__)
/*etc */ 

that works with structures or compound arrays.

#define STRUCTVAL_48(...) STRUCTVAL_32(__VA_ARGS__), STRUCTVAL_16(__VA_ARGS__)

struct Pair { char key[16]; char val[32]; };
struct Pair p_data[] = { STRUCTVAL_48("Key", "Value") };
int a_data[][4] = { STRUCTVAL_48(12, 19, 23, 37) };

macro names are negotiable.

Tags: C / Arrays / Initialization

Similar questions

Swift class: Fatal error: Use of unimplemented initializer 'init()' for class
I created a little convenience class for haptics and I try to reference the class in my Objc code: self.haptics = [[Haptics new] initWithStyle:UIImpactFeedbackStyleLight]; I get a crash on the Haptics class declaration: Fatal error: Use of unimplemented initializer 'init()' for class 'MyProject.Haptics' Not quite sure what I'm doing wrong here
Swift: "fatal error: use of unimplemented initializer 'init()' for class..."
This is a simple class I wanted to have instantiated with two arrays to populate an NSTableView on a mac app: When I step through the code as it is being initialized, everything works up to this point. Then I get this error: So I can can avoid this error, by adding the arrays optionals (not what I want as they are the tableView's dataSource) and ad...
Mixing objective-c and swift: fatal error: use of unimplemented initializer 'init(target:action:)' for class
my code contains both objective-c and swift classes and so far, everything worked pretty well. however, i added a custom gesture recognizer that inherits from UIGestureRecognizer. My code compiles but when I try to run it I get the following error: I assume that this error originates in the mix of objective-c and swift code but I have no clue how t...
fatal error: use of unimplemented initializer 'init(realm:schema:)' for class MyApp.User
Im getting this error when i try to load a user from the database. } I tried implemeting that init method but i get (Use of undeclared identifier RLMObjectSchema): Any hints?
fatal error: use of unimplemented initializer 'init(size:)' for class
I was testing my app on different devices and realized the sprite movements were quite inconsistent (running considerably faster on some devices as compared to others). I found this post and followed the instructions and removed the size parameters from all my SKScenes then I got the error: Please see my PosterScene class below and the GameViewCont...
fatal error: use of unimplemented initializer 'init()' for class
I'm using Realm-Cocoa in a mixed project. There have been a few head-scratchers, but now I'm truly stuck. I have tried tried several things but nothing helps. This class compiles with no complaints,but crashes at runtime: fatal error: use of unimplemented initializer 'init()' for class 'MyApp.Model' And here's the class:

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy.