使用平面陣列作為 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;
}
}
}