The question is currently problematic:
The answer in the question referenced above uses variable length array (VLA) features of C. These are not present in the C98 standard and are optional in the C11 standard.
The C standard prior to C99 (ISO/IEC 9899:1990) was C89 (ANSI) or C90 (ISO) — functionally the same standard. There was C++98 (ISO/IEC 14882:1998), but that's a wholly different language.
int main(void)
{
int a1=5;
int b1=6;
int a2=7;
int b2=8;
int arry1[a1][b1];
int arry2[a2][b2];
This sample code is using VLAs; it will not compile under strict C90 rules.
If you are constrained to the pre-1999 C standard, then you are constrained to using code similar to this. Clearly, you can initialize the arrays by reading data from a file or anything else that takes your fancy; using direct initializers is possible because the arrays are no longer VLAs.
#include <stdio.h>
void printArry(int d1, int d2, int *data);
int main(void)
{
enum { a1 = 5, b1 = 6, a2 = 7, b2 = 8 };
int arry1[a1][b1] =
{
{ 9, 8, 7, 6, 5, 4 },
{ 2, 3, 4, 3, 2, 1 },
{ -9, -8, -7, -6, -5, -4 },
{ 39, 38, 37, 36, 35, 34 },
{ 99, 98, 97, 96, 95, 94 },
};
int arry2[a2][b2] =
{
{ 198, 158, 165, 136, 198, 127, 119, 103, },
{ 146, 123, 123, 108, 168, 142, 119, 115, },
{ 160, 141, 168, 193, 152, 152, 147, 137, },
{ 144, 132, 187, 156, 188, 191, 196, 144, },
{ 197, 164, 108, 119, 196, 171, 185, 133, },
{ 107, 133, 184, 191, 166, 105, 145, 175, },
{ 199, 115, 197, 160, 114, 173, 176, 184, },
};
printArry(a1, b1, &arry1[0][0]);
printArry(a2, b2, &arry2[0][0]);
return 0;
}
void printArry(int d1, int d2, int *data)
{
int i, j;
for (i = 0; i < d1; i++)
{
for (j = 0; j < d2; j++)
printf(" %4d", data[i * d2 + j]);
putchar('\n');
}
}
The printArry()
function is, essentially, doing the index (subscript) calculation that you would like the compiler to do for you — but it can't because it is not able to handle C99 VLAs.
The first array of data is hand-crafted to allow problems to be spotted (such as using d1
instead of d2
in the subscript calculation). The second array of data is simply 56 random values between 100 and 199.
Sample output:
9 8 7 6 5 4
2 3 4 3 2 1
-9 -8 -7 -6 -5 -4
39 38 37 36 35 34
99 98 97 96 95 94
198 158 165 136 198 127 119 103
146 123 123 108 168 142 119 115
160 141 168 193 152 152 147 137
144 132 187 156 188 191 196 144
197 164 108 119 196 171 185 133
107 133 184 191 166 105 145 175
199 115 197 160 114 173 176 184