So as you know, in C function declarations, you have to name all dimension sizes but one of array parameters. I'm now working with a 2d array where both sizes are generated at runtime, however I want to pass that array to another function to fill it.
My thought was just using the maximum size in the function declaration, like this:
int max_size = 100;
int actual_size;
int another_size;
static void fill_array(int ar[][max_size])
{
for(int i = 0; i < another_size; i++)
{
for(int j = 0; j < actual_size; j++)
{
ar[i][j] = some int;
}
}
}
static void main()
{
if(some_input) actual_size = 50;
else actual_size = 100;
if(some_input) another_size = 10;
else another_size = 20;
int empty_array[another_size][actual_size] = {0};
fill_array(empty_array);
}
My thought is that even though the function may think that each array line has 100 ints, we're only filling the first 50 anyways. Is this unclever? Any way to accomplish the same more cleaner? Pretty new to C, so sorry if it's a very obvious thing.
For starters such a declaration of the function main
static void main()
is not standard.
The function should be declared like
int main( void )
If your compiler supports variable length arrays then you may declare the function like
static void fill_array( size_t rows, size_t cols, int ar[][cols] );
and pass a two-dimensional array of any sizes.
Here is a demonstrative program.
#include <stdio.h>
static void fill_array( size_t rows, size_t cols, int a[][cols] )
{
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ )
{
a[i][j] = i * cols + j;
}
}
}
int main(void)
{
size_t rows;
size_t cols;
printf( "Enter the number of rows: " );
scanf( "%zu", &rows );
printf( "Enter the number of columns: " );
scanf( "%zu", &cols );
int a[rows][cols];
fill_array( rows, cols, a );
for ( size_t i = 0; i < rows; i++ )
{
for ( size_t j = 0; j < cols; j++ )
{
printf( "%2d ", a[i][j] );
}
putchar( '\n' );
}
return 0;
}
Its output might look for example like
Enter the number of rows: 3
Enter the number of columns: 5
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14