2

Here is part of my code. I would like to initialize only the arraylist[0] as arraylist[0].x = 0 and arraylist[0].y = 0. I do not need to initialize the rest of the struct array. How can I do it? Thank you.

#include <stdio.h>
struct example {
    int x;
    int y;
};
struct example arraylist[40];

int main(int argc, char *argv[]){
    printf("%d\n %d\n", arraylist[0].x, arraylist[0].y);
    return 0;
}
2
  • AFAIK it's not possible in current C standards. C++ has a way for doing it, thought.
    – user529758
    May 19, 2012 at 12:51
  • You do not have the need to initialize the rest of the elements but it doesnt really hurt to initialize them and you should.
    – Alok Save
    May 19, 2012 at 12:52

4 Answers 4

5

You can initialise any particular element of the struct array.

For example:

struct example arraylist[40] = { [0]={0,0}}; //sets 0th element of struct

struct example arraylist[40] = { [5]={0,0}}; //sets 6th element of struct

This is called Designated Initializers which used to be a GNU extension before C99 adapted it and is also supported in standard C since C99.

3
  • 4
    However, once you have an initialiser for any part of the object, the entire object is initialised (to "zero of the appropriate type").
    – caf
    May 19, 2012 at 12:59
  • 1
    This is not a gnu extension but part of C99 (and C11). Gcc has this as an extension to tolerate it also in C89 mode. May 19, 2012 at 13:01
  • I agree. This is useful to set any value, not just 'zero for the type' and also accessing values which are not initialized is not going to correct anyway.
    – P.P
    May 19, 2012 at 13:03
2

Since you are talking about a variable in file scope, here, you don't have to do anything, since such variables are always initialized by 0 if you don't provide an explicit initializer.

1

In C, once you initialize part of a struct / array, you initialize the rest of it with 0.

You should have no problem with that, as you should not access uninitialized variables in first place, and their value is not defined.

1
  • AFAIR, that is even true for C++.
    – Alok Save
    May 19, 2012 at 12:53
1

In C all static and extern variables are initialized to 0 unless explicitly initialized otherwise.

2
  • ... if not initialized otherwise :) May 19, 2012 at 12:56
  • Edited to precise that you can explicitly initialize it otherwise. Thank you.
    – kmkaplan
    May 19, 2012 at 12:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.