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?

3
  • 5
    typedef struct { int cells[5][5]; } bingo_board; is a much more loop-friendly data structure. Commented Sep 9, 2011 at 4:56
  • Pretty new to C. I recognize that as an array, but do you think you could be a little more explicit? Thanks. Commented Sep 9, 2011 at 5: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). Commented Sep 9, 2011 at 5:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.