我有一个简单的函数 Bar
,它使用以数据结构数组形式传入的数据集中的一组值。数据可以来自两个来源:默认值的常量初始化数组,或动态更新的缓存。
调用函数决定使用哪些数据并应将其传递给 Bar
。
Bar
不需要编辑任何数据,事实上永远不应该这样做。我应该如何声明 Bar
的数据参数,以便我可以提供来自任一集合的数据?
union Foo
{
long _long;
int _int;
}
static const Foo DEFAULTS[8] = {1,10,100,1000,10000,100000,1000000,10000000};
static Foo Cache[8] = {0};
void Bar(Foo* dataSet, int len);//example function prototype
请注意,这是 C,而不是 C++,如果有区别的话;
编辑
哦,还有一件事。当我使用示例原型(prototype)时,我收到类型限定符不匹配警告,(因为我正在将可变引用传递给 const 数组?)。我必须为此更改什么?
最佳答案
你想要:
void Bar(const Foo *dataSet, int len);
参数声明const Foo *x
的意思是:
x
is a pointer to aFoo
that I promise not to change.
您将能够使用此原型(prototype)将非常量指针传递到 Bar
。
关于c - 如何将 const 数组或变量数组传递给 C 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046510/