使用平面阵列作为 2D 阵列
通常最简单的解决方案就是将 2D 和更高的数组作为平面内存传递。
/* create 2D array with dimensions determined at runtime */
double *matrix = malloc(width * height * sizeof(double));
/* initialise it (for the sake of illustration we want 1.0 on the diagonal) */
int x, y;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
if (x == y)
matrix[y * width + x] = 1.0;
else
matrix[y * width + x] = 0.0;
}
}
/* pass it to a subroutine */
manipulate_matrix(matrix, width, height);
/* do something with the matrix, e.g. scale by 2 */
void manipulate_matrix(double *matrix, int width, int height)
{
int x, y;
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
matrix[y * width + x] *= 2.0;
}
}
}