Danijel
Danijel

Reputation: 8606

Passing [CONST][] array to C function?

I am designing a C function interface which involves a 2d array. The problem is, row dimension is constant, and column one should be user defined.

#define ROWS (65)
void init(int columns, float array[ROWS?][columns?])
{
   ...
}

void main()
{
    float array1[ROWS][30]; 
    float array2[ROWS][50]; 
    init(30, array1); 
    init(50, array2); 
} 

How do I design an interface to be able to pass this kind of array down to function?

p.s.
Can't do it the other way around, where columns would be constant, because must use some 3rd pary libraries that want it this way.

Upvotes: 0

Views: 1064

Answers (2)

You mentioned in a comment. So it shouldn't be too difficult to approximate what you want. In fact, you are almost there yourself. It can look like this:

#define ROWS 65
void init(int columns, float array[static ROWS][columns])
{

}

Now array is of a variably modified type, and columns is user defined. static ROWS means callers must pass in an array of at least 65 rows, or undefined behavior will ensue. That's pretty much as close to forcing them to pass 65 as you can.

Upvotes: 3

Lundin
Lundin

Reputation: 213832

Simply do as you wrote in your example

void init (size_t rows, size_t columns, float array[rows][columns])

Then you can pass compile-time constants or run-time variables to the function as you please. You'll also need to have C compiler from the current millennium (C99 or later).

Upvotes: 4

Related Questions