如何快速填充结构值?

the*_*er3 1 c arrays structure

我使用Visual Studio 2013与标准C.

我的程序需要四行才能 {"Analysis 1", "AN 1", 0, 0.0667}输入Fach[0].

我不想浪费这么多行来填充这个数组.

有没有更好的方法将这四行合二为一?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*ack 7

在C99中,您已指定初始值设定项,还有复合初始值设定项(但我不记得它们是扩展名还是标准支持):

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;
}
Run Code Online (Sandbox Code Playgroud)


M O*_*ehm 7

您可以在定义时初始化整个数组:

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},
    ...
};
Run Code Online (Sandbox Code Playgroud)

外括号表示阵列.如果初始化数组,则可以省略维度; 否则剩余的数组条目为零.

内括号表示结构.如果你感觉很啰嗦,你可以像杰克给你看的那样使用指定的初始化程序.

如果要在初始化后分配整个结构,则必须使用Basile所示的复合文字.