Ian Lundberg
Ian Lundberg

Reputation: 1883

Can you create an array inside of a struct initialization?

So I have a struct:

typedef struct Board {
    size_t size;
    char* board;
} Board;

I was wondering if it was possible to then do something like this, during initialization of the struct:

Board boardStruct = {
    solutionLength, 
    char emptyBoard[size]
};

Unfortunately, when I try to do it this way I get the compilation error: expected expression before 'char'

Any ideas? I'm trying to avoid declaring the array outside of the struct initialization, but if that is the only option I guess that is the route I will have to go with.

Upvotes: 2

Views: 71

Answers (2)

Nick ODell
Nick ODell

Reputation: 25354

@bruno's solution will work. Another thing you could try is to put the array within the Board struct. E.g:

typedef struct Board {
    size_t size;
    char board[size];
} Board;

Upside: Avoids a malloc/free for each Board.
Downside: Board is larger, so it costs more to copy it. Also, you must know how big the board is before your program runs.

Upvotes: 0

bruno
bruno

Reputation: 32596

You can do something like that :

#include <stdlib.h>

typedef struct Board {
    size_t size;
    char* board;
} Board;

int main()
{
  const int solutionLength = 3; /* or #define solutionLength 3 */

  Board boardStruct = {
    solutionLength, 
    malloc(solutionLength)
  };

  return 0;
}

or closer to your proposal :

#include <stdlib.h>

typedef struct Board {
    size_t size;
    char* board;
} Board;


int main()
{
  const int solutionLength = 3; /* or #define solutionLength 3 */
  char emptyBoard[solutionLength];

  Board boardStruct = {
    solutionLength, 
    emptyBoard
  };

  return 0;
}

Upvotes: 3

Related Questions