简体   繁体   English

如何在结构中填充和构造?

[英]How do I fill and struct within struct?

I am tryng to fill and struct within struct with array.我正在尝试用数组在结构中填充和构造。 Is there any way I can do it?有什么办法可以做到吗? I tried loops and simply just putting array instead of hard numbers but no luck.我尝试了循环,只是简单地放置数组而不是硬数字,但没有运气。 Here code:这里的代码:

typedef struct
{
    int *tokens;
    char *name;
    int numTokens;
    int index;
} Pile;

typedef struct
{
    Pile N;
    Pile W;
    Pile E;
    Pile S;
} Game;

int main(void)
{
    //tokens
    int north[MAX_TOKENS], west[MAX_TOKENS], east[MAX_TOKENS], south[MAX_TOKENS];
    // sizes of token value fields
    int north_size = 0, west_size = 0, east_size = 0, south_size = 0;
    int check = read_tokens(north, west, east, south, &north_size, &west_size, &east_size, &south_size);
    //I read them and then store backwards.
    int *arrays[4] = {north, west, east, south};
    int sizes[4] = {north_size, west_size, east_size, south_size};
    store_values_backwards(arrays, sizes);
    //Then I need to send arrays with the numbers I read into this
        Pile N = {(int[]){*north}, "N", north_size, 0};
        Pile W = {(int[]){*west}, "W", west_size, 0};
        Pile E = {(int[]){*east}, "E", east_size, 0};
        Pile S = {(int[]){*south}, "S", south_size, 0};

Instead of hard coded numbers like:而不是像这样的硬编码数字:

  Pile N = {(int[]){-66, -52, 109}, "N", 3, 0};
  Pile W = {(int[]){78}, "W", 1, 0};
  Pile E = {(int[]){118,146,46,77}, "E", 4, 0};
  Pile S = {(int[]){67,159,-13}, "S", 3, 0};

The first member of the struct is a pointer to int ( int *tokens; ) and you want to initialize it using an array of int s.struct的第一个成员是指向int ( int *tokens; ) 的指针,您希望使用int数组对其进行初始化。

Then然后

Pile N = {&north[0], "N", north_size, 0};

or simply或者简单地

Pile N = {north, "N", north_size, 0};

should work.应该管用。

Take a look to the C-FAQ :查看C-FAQ

A reference to an object of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element;出现在表达式中的对 T 数组类型对象的引用衰减(除了三个例外)为指向其第一个元素的指针; the type of the resultant pointer is pointer-to-T.结果指针的类型是指向 T 的指针。

That is, whenever an array appears in an expression, the compiler implicitly generates a pointer to the array's first element, just as if the programmer had written &a[0].也就是说,无论何时数组出现在表达式中,编译器都会隐式生成一个指向数组第一个元素的指针,就像程序员编写了 &a[0] 一样。 (The exceptions are when the array is the operand of a sizeof or & operator, or is a string literal initializer for a character array. (例外情况是数组是 sizeof 或 & 运算符的操作数,或者是字符数组的字符串文字初始值设定项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM