如何将const数组或变量数组传递给C中的函数?

时间:2021-04-26 04:15:17

I have a simple function Bar that uses a set of values from a data set that is passed in in the form of an Array of data structures. The data can come from two sources: a constant initialized array of default values, or a dynamically updated cache.

我有一个简单的函数Bar,它使用一组数据集中的值,这些数据集以数据结构数组的形式传入。数据可以来自两个来源:默认值的常量初始化数组或动态更新的缓存。

The calling function determines which data is used and should be passed to Bar. Bar doesn't need to edit any of the data and in fact should never do so. How should I declare Bar's data parameter so that I can provide data from either set?

调用函数确定使用哪些数据并应传递给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

Note, this is C, NOT C++ if that makes a difference;

注意,这是C,而不是C ++,如果这有所不同;

Edit
Oh, one more thing. When I use the example prototype I get a type qualifier mismatch warning, (because I'm passing a mutable reference to a const array?). What do I have to change for that?

编辑哦,还有一件事。当我使用示例原型时,我得到一个类型限定符不匹配警告,(因为我将一个可变引用传递给const数组?)。我需要改变什么呢?

2 个解决方案

#1


8  

You want:

void Bar(const Foo *dataSet, int len);

The parameter declaration const Foo *x means:

参数声明const Foo * x表示:

x is a pointer to a Foo that I promise not to change.

x是一个指向Foo的指针,我保证不会改变。

You will be able to pass a non-const pointer into Bar with this prototype.

您将能够使用此原型将非const指针传递到Bar。

#2


0  

As you have done - the function takes a pointer to the data (const if it doesn't need to change it)

正如您所做的那样 - 该函数采用指向数据的指针(如果不需要更改,则为const)

Then either pass the pointer if you allocated the data with malloc, or the first element if this is a static array.

然后,如果使用malloc分配数据,则传递指针;如果是静态数组,则传递第一个元素。

#1


8  

You want:

void Bar(const Foo *dataSet, int len);

The parameter declaration const Foo *x means:

参数声明const Foo * x表示:

x is a pointer to a Foo that I promise not to change.

x是一个指向Foo的指针,我保证不会改变。

You will be able to pass a non-const pointer into Bar with this prototype.

您将能够使用此原型将非const指针传递到Bar。

#2


0  

As you have done - the function takes a pointer to the data (const if it doesn't need to change it)

正如您所做的那样 - 该函数采用指向数据的指针(如果不需要更改,则为const)

Then either pass the pointer if you allocated the data with malloc, or the first element if this is a static array.

然后,如果使用malloc分配数据,则传递指针;如果是静态数组,则传递第一个元素。