【发布时间】:2010-12-02 19:23:18
【问题描述】:
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();
(struct foo 在 foo.h 中声明)
此代码必须在没有硬编码 Bars 数字的情况下执行,因为 Bars 的数量会根据用户设置的 DIP 开关而改变。现在我无法初始化 myFoo;我收到错误“初始化程序中预期的常量表达式”。我是否必须像这样初始化它:
struct foo myFoo[];
稍后再更改?如果是这样,我如何使 myFoo[] 长度正确?我显然没有与所需大小相对应的常量。我需要动态分配这个吗?
我找到了这个类似的答案,但对我没有太大帮助 - C++ a class with an array of structs, without knowing how large an array I need
【问题讨论】:
标签: c struct compilation