Reputation: 15110
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.
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?
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;
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?
Upvotes: 8
Views: 13343
Reputation: 28010
You want:
void Bar(const Foo *dataSet, int len);
The parameter declaration const Foo *x
means:
x
is a pointer to aFoo
that I promise not to change.
You will be able to pass a non-const pointer into Bar
with this prototype.
Upvotes: 10
Reputation: 96109
As you have done - the function takes a pointer to the data (const if it doesn't need to change it)
Then either pass the pointer if you allocated the data with malloc, or the first element if this is a static array.
Upvotes: 0