4

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?

zeboidlund
  • 9,731
  • 31
  • 118
  • 180
  • 5
    `typedef struct { int cells[5][5]; } bingo_board;` is a much more loop-friendly data structure. – James McNellis Sep 09 '11 at 04:56
  • Pretty new to C. I recognize that as an array, but do you think you could be a little more explicit? Thanks. – zeboidlund Sep 09 '11 at 05:00
  • 1
    It is a two dimensional array (five elements by five elements) of integers. A `bingo_board` named `x` can be accessed as x.cells[row][column]. This is much easier to handle in a loop than having to write separate cases for each row or column. With your implementation, you have to write separate code for `x.one.a` and `x.four.a` (you have to write at least ten cases, one for each row and column). – James McNellis Sep 09 '11 at 05:03

2 Answers2

4

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
1

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.

Dave
  • 10,964
  • 3
  • 32
  • 54