Arrays in C are basically pointers. The only real difference is that the compiler knows to how many elements it points to.
That means that wherever your code expects a pointer, you can use an array's name instead as it will implicitly be converted to a pointer to its first element.
As mentioned, the important difference between arrays and pointers is the result of the sizeof()
operator: For pointers, it will return the number of bytes needed to store the pointer, for arrays, it will return the number of bytes needed to store the elements!
Therefore, it's possible to determine the number of elements in an array with the following macro:
#define count(ARRAY) (sizeof(ARRAY)/sizeof(*ARRAY))
Instead of *ARRAY
, you could use ARRAY[0]
as well.
Anyway, to pass an array to a function, just treat it as a pointer. Because the compiler won't know the number of elements it contains (it looses this information during the conversion), pass another argument specifying this as well:
void func(struct ABC * array, size_t elementCount) {...}
struct ABC anArray[2] = {...};
func(anArray, count(anArray));
We use our count()
macro so that we need to change the array's size only in one place.
So, why does your function expect a double pointer? Most likely, to allow the elements of the array to be arbitrarily placed in memory. So if you stored your elements in a plain old array, you have to convert it:
struct ABC array[2] = {...};
struct ABC * parray[count(array)];
for(size_t i = 0; i < count(array); ++i)
parray[i] = &array[i];
Also, if func
really doesn't accept a second argument for the array's size, this could mean that it either only accepts arrays of a certain size (then, the function's signature should have been something like func(struct ABC * array[5])
), or, that it expects a certain element to signify the end of the array (most likely NULL
). In that case, you have to do
struct ABC * parray[count(array) + 1];
parray[count(array)] = NULL;
Also, another solution would be to use a two-dimensional array:
struct ABC parray[][1] = {
{ {/* first struct's initializer */} },
{ {/* second struct's initializer */} },
{ {/* third struct's initializer */} }
};
func(parray, count(parray));