Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a const array or a variable array to a function in C?

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?

like image 316
CodeFusionMobile Avatar asked Jun 15 '10 15:06

CodeFusionMobile


People also ask

How can we pass array to function in C?

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.

How do you pass an array to a function explain?

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.

Can const array be pushed?

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.

Why can arrays be passed by values to functions?

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.


1 Answers

You want:

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

The parameter declaration const Foo *x means:

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

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

like image 64
psmears Avatar answered Nov 08 '22 21:11

psmears