1

How can a large sparse array be initialized conveniently in C? The code below works but becomes unwieldy for large arrays, basically a whole new way for off by one errors! For example, what if I want an array of length 200 all 0's except for 1's at indices 7, 62, 100, and 189. The values are known at compile time. I was wondering if macros can generate the array.

const char myArray[] = {0,0,1,0,0,0,0,0,1,0};

This question is for C++, but maybe a trick with structures would work in C also.

1
  • Initialization is either all or nothing in C. There are short-cuts in notation, but the result is still all or nothing. Is your goal a short notation or a partial initialization? Commented Nov 19, 2016 at 2:43

3 Answers 3

17

I don't know how to build macros to achieve that, but if you use C99 or later, you can use designated initializers like this:

const char myArray[200] = {
    [7] = 1,
    [62] = 1,
    [100] = 1,
    [189] = 1
};
Sign up to request clarification or add additional context in comments.

1 Comment

good one! Members of an aggregate that are not explicitly initialized are initialized to zero by default.
1

If you have C99 you should use another answer here, but if not....

Use code generation. I've used Python Mako or just plain Python before, to generate code similar to what you need for this.

If you have to use just C89, I would do this:

#define TEN_ZEROS 0,0,0,0,0,0,0,0,0,0

const char myArray[] = {
    0,0,0,0,0,0,0,1,0,0,
    TEN_ZEROS,
    TEN_ZEROS,
    TEN_ZEROS,
    TEN_ZEROS,
    TEN_ZEROS,
    0,1 /*...*/
};

Comments

1

The standard garanties that if you have the size defined and you init the arry partially the remainings get set to 0 So

int myarray[200]={0}; //this set all the array to 0;
myarray[7]=23;
   ....

Otherwise

 static int myarray[200]; //also all the static variable get set to 0
  myarray[7]=23;

Or the last one

  memeset(myarray, 0, sizeof(myarray))
  myarray[7]=23;

These are all to prefer as list or other solutions, since is istantly clear what you did, there is no risk to initalize the wrong item, (a list of 200 items is quite hard to check) and if you have to change something is quite fast change exactly the correct index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.