[英]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'
不幸的是,当我尝试以这种方式进行操作时,出现编译错误:
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. @bruno的解决方案将起作用。 Another thing you could try is to put the array within the Board struct.
您可以尝试的另一件事是将数组放入Board结构中。 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.
另外,在程序运行之前,您必须知道电路板的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.