0

到目前为止,我有以下代码,我很确定我可以用多个语句进行显式初始化,但我想学习如何用一个语句来做。

#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};
4

4 回答 4

3

你快到了:

 = { [0] = {"apple pie", 4, 100}, [1] = {"salsa", 2, 80} }

将是您的数组的初始化。

仅当您的编译器支持 C99 附带的“指定”初始化程序时。

除此以外

 = { {"apple pie", 4, 100}, {"salsa", 2, 80} }

也会这样做。

于 2012-11-12T18:57:11.913 回答
2

尝试:

struct { ... } lunch[LUNCHES] = {{"apple pie", 4,100}, {"salsa",2,80}};
于 2012-11-12T18:57:42.380 回答
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}};
}
于 2012-11-12T18:57:46.000 回答
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;
}
于 2012-11-12T18:59:39.987 回答