到目前为止,我有以下代码,我很确定我可以使用多个语句进行显式初始化,但我想学习如何使用单个语句。
#include <stdio.h>
#include <stdlib.h>
#define LUNCHES 5
int main(void)
{
struct Food
{
char *n; /* “n” attribute of food */
int w, c; /* “w” and “c” attributes of food */
}
lunch[LUNCHES],
lunch[0] = {"apple pie", 4, 100},
lunch[1] = {"salsa", 2, 80};
}
我认为以下内容可行,但这是另一种说法。
int main(void)
{
struct Food
{
char *n; /* “n” attribute of food */
int w, c; /* “w” and “c” attributes of food */
}
lunch[LUNCHES];
lunch[0] = {"apple pie", 4, 100};
lunch[1] = {"salsa", 2, 80};
答案 0 :(得分:3)
你快到了:
= { [0] = {"apple pie", 4, 100}, [1] = {"salsa", 2, 80} }
将是您阵列的初始化。
仅当您的编译器支持C99附带的“指定”初始值设定项时。
,否则
= { {"apple pie", 4, 100}, {"salsa", 2, 80} }
也会这样做。
答案 1 :(得分:2)
尝试:
struct { ... } lunch[LUNCHES] = {{"apple pie", 4,100}, {"salsa",2,80}};
答案 2 :(得分:2)
你可以用这种方式定义
int main(void)
{
struct Food
{
char *n; /* “n” attribute of food */
int w, c; /* “w” and “c” attributes of food */
}lunch[LUNCHES] = { {"apple pie", 4, 100}, {"salsa", 2, 80}};
}
答案 3 :(得分:1)
或许这样的事情?
#include <stdio.h>
#include <stdlib.h>
#define LUNCHES 5
struct Food {
char *n; /* “n” attribute of food */
int w, c; /* “w” and “c” attributes of food */
} lunch[LUNCHES] = {
{"apple pie", 4, 100},
{"salsa", 2, 80}
};
int
main(void)
{
printf ("lunches[0].n= %s\n", lunches[0].n);
return 0;
}