我正在尝试创建一个引用自身内部变量的结构。我该怎么做呢?

I am trying to make a struct that references a variable within itself. How do i do this?

代码如下:

int main()
{
    struct board
    {
        int length_x;
        int length_y;

        int board_size = length_x*length_y;
    };
    struct board chess_board ={
        8,8
    };
    return 0;
}

这个returns错误

error: variable-sized object may not be initialized

我已经使它比我实际编码的要简单得多,但我想要的只是当我制作一个结构时它会执行该操作。

在 C 中,您不能在结构定义中初始化结构的数据成员。

所以这个结构定义

struct board
{
    int length_x;
    int length_y;

    int board_size = length_x*length_y;
};

不正确。

你应该写

struct board
{
    int length_x;
    int length_y;

    int board_size;
};

然后

struct board chess_board ={ 8, 8, 64 };

或者例如

struct board chess_board =
{ 
    .length_x = 8, .length_y = 8, .board_size = 64 
};

引入一个常量就好了

enum { N = 8 };

然后写

struct board chess_board =
{ 
    .length_x = N, .length_y = N, .board_size = N * N 
};

或者您可以编写一个单独的函数来初始化结构类型对象的数据成员。

例如

void init_board( struct board *board, int n )
{
    board->length_x = n;
    board->length_y = n;
    board->board_size = n * n;
}

并且在声明结构 stype 的 n 个对象之后,您可以调用该函数

struct board chess_board;
init_board( &chess_board, 8 );

您可以使用宏来制作智能初始化器

#define BOARD_INIT(N) { (N), (N), (N) * (N) }

struct board b = BOARD_INIT(8);

在 C99 中,您还可以使用复合文字和指定的初始值设定项来添加一些类型安全性

#define BOARD_INIT(N) (struct board) { \
  .length_x = (N),                     \
  .length_y = (N),                     \
  .board_size = (N) * (N)              \
}

实际上,可以进行“自引用”,因为初始化变量的名称在初始化列表中是可见的。

struct board b = {
  .length_x = 8,
  .length_y = 8,
  .board_size = b.length_x * b.length_y,
};

根据6.7.9p19

The initialization shall occur in initializer list order the values of b.length_x and b.length_y should be ready when b.board_size is initialized.