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?
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
In order to pass an array as call by value, we have to wrap the array inside a structure and have to assign the values to that array using an object of that structure. This will help us create a new copy of the array that we are passing as an argument to a function. Let's understand this with a simple example.
Const Arrays For example, you can add another number to the numbers array by using the push method. Methods are actions you perform on the array or object. const numbers = [1,2,3]; numbers. push(4); console.
Arrays are not passed by value because arrays are essentially continuous blocks of memmory. If you had an array you wanted to pass by value, you could declare it within a structure and then access it through the structure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With