简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM