zeboidlund
zeboidlund

Reputation: 10137

initialize a struct within a struct initialization?

This may sound somewhat stupid, but I have to know as I'm writing a bingo board in C.

#include <stdio.h>
typedef struct {
    int a;
    int b;
    int c;
    int d;
    int e;
} row;

typedef struct {
    row one;
    row two;
    row three;
    row four;
    row five;   
} bingo_board;

void initialize_columns()
{
    bingo_board board = {
    .one = {1, 2, 3, 4, 5},
    .two = {6, 7, 8, 9, 10},
    .three = {11, 12, 13, 14, 15},
    .four = {16, 17, 18, 19, 20},
    .five = {21, 22, 23, 24, 25}
    };
}

Is this possible?

Upvotes: 4

Views: 5389

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320541

It can be done simply as

void initialize_columns()
{
    bingo_board board = {
      {1, 2, 3, 4, 5},
      {6, 7, 8, 9, 10},
      {11, 12, 13, 14, 15},
      {16, 17, 18, 19, 20},
      {21, 22, 23, 24, 25}
    };
}

Or even as

void initialize_columns()
{
    bingo_board board = {
      1, 2, 3, 4, 5,
      6, 7, 8, 9, 10,
      11, 12, 13, 14, 15,
      16, 17, 18, 19, 20,
      21, 22, 23, 24, 25
    };
}

No need to "tag" every row. The tagged syntax is available in C99 though, and what you have in your example is already correct for C99.

Upvotes: 4

Dave
Dave

Reputation: 11162

Because structs are first class citizens in c, assignment is well defined, this lets you

static bingo_board initial_board = {
    {1, 2, 3, 4, 5},
    {6, 7, 8, 9, 10},
    {11, 12, 13, 14, 15},
    {16, 17, 18, 19, 20},
    {21, 22, 23, 24, 25}
};


void init_board(bingo_board *b)
{
    *b = initial_board;
}

Which seems to be what you want. If you do declare the board within the function, I would suggest declaring it static, because you don't modify it, so persistent changes are ok, and so that the function doesn't have to grow the stack as much on every call.

Upvotes: 1

Related Questions