How to convert a multi-dimensional array in C language into a one-dimensional array?

One way to convert a multidimensional array to a one-dimensional array is by iterating through the multidimensional array and storing each element in the one-dimensional array sequentially.

Here is an example code demonstrating how to flatten a 2-dimensional array into a 1-dimensional array:

#include <stdio.h>

void convertTo1D(int arr[][3], int rows, int cols, int* result) {
    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[k++] = arr[i][j];
        }
    }
}

int main() {
    int arr[][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int rows = sizeof(arr) / sizeof(arr[0]); // 计算行数
    int cols = sizeof(arr[0]) / sizeof(arr[0][0]); // 计算列数
    int size = rows * cols; // 一维数组的大小
    int result[size]; // 定义一维数组

    convertTo1D(arr, rows, cols, result);

    // 打印一维数组
    for (int i = 0; i < size; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    return 0;
}

Running this code will produce: 1 2 3 4 5 6 7 8 9.

bannerAds