With your typedef
as follows:
enum { IDL = 10 };
typedef struct {
char id[IDL];
int value;
} obj;
If you are intent on using a 2D VLA, then you are better off thinking of passing the address of the first row, rather than the address of the first element. (even though the two address are the same) Why? An array (e.g. obj o[i][j];
) when passed as a parameter to a function will have the first level of indirection converted to a pointer (e.g. obj o[i][j]
becomes obj (*o)[j]
).
Take for example your VLA declared in main
as follows:
obj o[i][j]; /* declare VLA */
So your function declaration will need to match (and since the number of columns is non-constant, be in the correct order) For instance:
int sum_all_elements (int i, int j, obj (*obj_ptr)[j]);
You can then call the function within your program as, for example:
printf ("\n sum : %d\n\n", sum_all_elements (i, j, &o[0]));
which is simply equivalent to:
printf ("\n sum : %d\n\n", sum_all_elements (i, j, o));
Putting a short example together (and just filling obj[a][b].value = a + b;
), you can do something similar to the following:
#include <stdio.h>
enum { IDL = 10 };
typedef struct {
char id[IDL];
int value;
} obj;
int sum_all_elements (int i, int j, obj (*obj_ptr)[j]);
int main (void) {
int i, j;
printf ("\n enter i & j: ");
if (scanf (" %d %d", &i, &j) != 2) {
fprintf (stderr, "error: invalid input, i, j.\n");
return 1;
}
obj o[i][j]; /* declare VLA */
for (int a = 0; a < i; a++)
for (int b = 0; b < j; b++)
o[a][b].value = a + b; /* fill value with misc a + b */
printf ("\n sum : %d\n\n", sum_all_elements (i, j, o));
return 0;
}
/* some all .value for i x j array of obj */
int sum_all_elements (int i, int j, obj (*obj_ptr)[j])
{
int sum = 0;
for (int a = 0; a < i; a++)
for (int b = 0; b < j; b++)
sum += obj_ptr[a][b].value;
return sum;
}
Example Use/Output
$ ./bin/p2p2a
enter i & j: 10 10
sum : 900