Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Initializing struct member array in C?

/*

I have this structure, and in it is an array, and I can not seem initialize the array without getting compile errors.

this is basically what I'm trying to do looks like:

*/

struct foo {

int bar[8] = { 1,2,3,4,5,6,7,8, };

};

3 Answers

Relevance
  • Anonymous
    1 decade ago
    Favorite Answer

    You misses definition and initialization: The correct looks like:

    struct foo {

    int bar[8];

    } x = { { 1,2,3,4,5,6,7,8 } };

    //Now you can access like this:

    x.bar[1];

    Thx. Hope it is useful

    More: you can only initialize a variable not a structure.

    /ucmapi (http://www.ucmapi.com)/

  • ?
    Lv 4
    5 years ago

    it is between the relaxing factors of C programming. A char array in C is terminated by ability of technique of a null personality, escaped as ''. The char array could also be terminated by ability of making use of the dimensions of the array notwithstanding there's no such ensure in C. for this reason causing a lot of mistakes the position the array is accessed out of bounds. So by using initialising your structure with 0 you're putting a null ('') in component 0 of list and a nil in age. The null in component 0 shows that your char array has a usable length of 0. have relaxing.

  • 1 decade ago

    Hmm... I have done a bit of classes in C++ and if what they say that the only difference between classes and structures is that the members in structures are public by default and the member in classes are private in default, then you can use constructors.

    Sample code:

    struct somestruct{

    int someint[5];

    somestruct{

    someint[0] = ...;

    //and so on... use a loop for big arrays :)

    }

    }

Still have questions? Get your answers by asking now.