foo.c
#include "main.h"
unsigned char currentBar;
struct foo myFoo[getNumBars()];
void initMyFoo(void)
{
currentBar=(getNumBars()-1);
for(i=0; i<(sizeof(myFoo)/sizeof(myFoo[0])); i++)
{
myFoo[i].we = 1;
myFoo[i].want = 0;
myFoo[i].your = 0;
myFoo[i].soul = 0;
}
}
main.c
#include "foo.h"
unsigned char getNumBars()
{
return getDipSwitchValues();
}
initMyFoo();
(在foo.h中声明了foo结构。)
此代码必须在不对Bars进行硬编码的情况下执行,因为Bars的数量将根据用户设置其DIP开关的方式而改变。现在,我无法初始化myFoo。我收到错误“初始化程序中需要常量表达式”。我是否必须像这样初始化它:
struct foo myFoo[];
以后再更改?如果是这样,如何使myFoo []正确长度?我显然没有对应于所需大小的常数。我是否需要动态分配此内容?
我找到了类似的答案,但对我没有太大帮助-C++ a class with an array of structs, without knowing how large an array I need
最佳答案
struct foo* myFoo;
unsigned int myFooSize;
void initMyFoo(void)
{
myFooSize = getNumBars();
myFoo = malloc(myFooSize * sizeof(*myFoo));
for (i=0; i<myFooSize; i++) {
/* ... */
}
}
void cleanupMyFoo(void)
{
free(myFoo);
myFoo = NULL;
myFooSize = 0;
}