Home > Software engineering >  How do I fill and struct within struct?
How do I fill and struct within struct?

Time:12-19

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

CodePudding user response:

The first member of the struct is a pointer to int (int *tokens;) and you want to initialize it using an array of ints.

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:

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; the type of the resultant pointer is pointer-to-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]. (The exceptions are when the array is the operand of a sizeof or & operator, or is a string literal initializer for a character array.

  • Related