thefighter3
thefighter3

Reputation: 101

How can I fill a Structure with values quickly?

I am using Visual studios 2013 with Standard C.

My program takes four lines to put {"Analysis 1", "AN 1", 0, 0.0667} in Fach[0].

I don't want to waste so many lines to fill this Array.

Is there a better way to put this four lines into one?

#define _CRT_SECURE_NO_WARNINGS
#include "header.h"
#include <stdio.h>
#include <string.h>

struct sFach
{
    char Mod[40];       //Modulbezeichnung
    char Ab[5];         //Abkürtzung
    int Note;           //Note
    double Gew;         //Gewichtungsfaktor
};

int main()
{
    struct sFach Fach[31];

    strcpy(Fach[0].Mod, "Analysis 1");
    strcpy(Fach[0].Ab, "AN 1");
    Fach[0].Note = 0;
    Fach[0].Gew = 0.0667;

    strcpy(Fach[1].Mod, "Algebra");
    strcpy(Fach[1].Ab, "AL");
    Fach[1].Note = 0;
    Fach[1].Gew = 0.0889;

    return 0;
}

Upvotes: 2

Views: 24766

Answers (3)

M Oehm
M Oehm

Reputation: 29126

You can initialise the whole array when you define it:

struct sFach Fach[] = {
    {"Analysis 1",      "AN1",  0,  0.0667},
    {"Algebra",         "AL",   0,  0.0889},
    {"Kunst 1",         "K1",   0,  0.1},
    {"Kunst 2",         "K2",   0,  0.1},
    {"Kunst 3",         "K3",   0,  0.1},
    {"Heimatkunde",     "HK",   0,  0.05},
    ...
};

The outer braces denote the array. You can leave out the dimension if you initialise the array; otherwise the remaining array entries are zero.

The inner braces denote the structs. If you are feeling verbose you can use designated initialisers as Jack has shown you.

If you want to assign whole structs after initialisation, you have to use the compound literal as shown by Basile.

Upvotes: 10

With a recent (C11 conforming) compiler, you might try:

Fach[0] = (struct sFach){"Analysis 1","AN 1",0,0.667};

and so on for the next entries...

(an optimizing compiler would make that code quite efficient)

Another possibility would be to write some script (e.g. in GNU awk, in Python, etc...) which would parse some data file and generate (from that data file) some initialize_Fach.inc file containing lines like above, and just add #include "initialize_Gach.inc" in your C code. Of course, you'll need to modify your build process (e.g. improve your Makefile or perhaps some Microsoft .vproj thing).

Don't forget that C code, in particular for initialization, can be generated by something else.

Upvotes: 2

Jack
Jack

Reputation: 133609

In C99 you have designated initializers, and also compound initializers (but I don't remember if they are an extension or supported by standard):

struct sFach
{
    char Mod[40];       //Modulbezeichnung
    char Ab[5];         //Abkürtzung
    int Note;           //Note
    double Gew;         //Gewichtungsfaktor
};

int main()
{
    struct sFach foo = { .Mod = "foo", .Ab = "bar", .Note = 10, .Gew = 10.0 };   
    struct sFach foo2 = { "foo", "bar", 10, 10.0 }; 
    return 0;
}

Upvotes: 9

Related Questions