I have not been able to find examples that initialize two-dimension array at run-time.
This is code in perl; can anyone "translate" this code into C?
my @grid; # grid = 2D array
my $gr=0; # rows in grid
my $gc=0; # cols in grid
my @ct;
if( $ARGV[0] eq '5x5' ) {
$gr=5; $gc=5; # grid is all zeroes
@ct=(2,2,2,2,0);
}
if( $ARGV[0] eq '9x9' ) {
$gr=9; $gc=9; # grid is all zeroes
@ct=(2,3,4,2,3,5,3,5,3);
}
if( $ARGV[0] eq '6x10' ) {
$gr=6; $gc=10;
@grid = (
[0,8,0,0,0,9,3,5,6,7],
[6,0,0,5,0,7,0,0,1,0],
[5,0,2,0,4,1,0,0,0,0],
[0,0,0,0,2,0,0,0,0,1],
[0,0,0,1,0,0,0,0,0,0],
[1,5,0,4,2,6,8,0,0,0],
);
@ct=(14,41,15,29,26,33,32,27,32,21);
}
malloc()with pointer. you can then treat it like an array withptr[1]for example. if you insist of having an real array at runtime it is not possible, at least at C89. This is because arrays in C are stack - allocated, and you need to specify the size at compile time. If it is fine with you just useint foo[5]