I would like to define a custom structure that contains two dynamically allocatable integer arrays a
and b
. In order to allocate memory for the arrays and initialise arrays with values I have written a "constructor" function initp
. My approach is presented below.
A custom structure called pair
:
typedef struct {
...
int l; // length of compositions
int k; // no. of elements in compositions
int *a; // composition 1
int *b; // composition 2
} pair;
A function to initialise custom structure:
int initp(..., int l, int k, int a[], int b[], pair *f) {
...
f->l = l;
f->k = k;
// allocate composition arrays
f->a = (int *) calloc(l, sizeof(int));
f->b = (int *) calloc(l, sizeof(int));
// initialise composition arrays
for (int i = 0; i < k; i++) {
f->a[i] = a[i];
f->b[i] = b[i];
}
}
A function call in the main program:
// initialise pairs
pair f1, f2;
initp(..., 10, 2, (int[]){3, 4}, (int[]){7, 6}, &f1);
initp(..., 10, 1, (int[]){4}, (int[]){9}, &f2);
I'm on a mission to write an "elegant" code. Therefore, the questions I have are:
- Is it possible to avoid specifying the no. of elements in arrays
a
andb
passed to theinitp
? This is the parameterk
. In the above examples it is 2 and 1. - Is it possible to avoid "explicit" casting with
(int[])
in the function call? - Please let me know, if you have general comments and criticism on improving the quality of the code.