簡體   English   中英

在 C 中將 2D 數組轉換為 1D

[英]Converting 2D array to 1D in C

我創建了一個 2d 數組,用戶可以在其中寫入大小(列和行)並用隨機數填充它,但我無法從 2d 轉換為 1d。 我的問題是如何將 2d 數組轉換為 1d(就像我正在創建 3x3 數組,例如 92 88 4 下一行 6 10 36 下一行 96 66 83,我想將其轉換為 92 88 4 6 10 36 96 66 83) . 如果我的代碼有問題,請告訴我。 (對不起我的語法錯誤)

這是我的代碼;

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("Enter the number of rows: ");
    int i; 
    scanf("%d", &i);

    printf("Enter the number of columns: ");
    int y; 
    scanf("%d", &y);

    int array[i][y];
    int rows, columns;
    int random;

    srand((unsigned)time(NULL));

    for(rows=0;rows<i;rows++)
        {
            for(columns=0;columns<y;columns++)
                {
                    random=rand()%100+1;

                    array[rows][columns] = random;
                    printf("%i\t",array[rows][columns]);
                }

            printf("\n");
        }

return 0;
}
#include <stdio.h>

int main()
{
    int i = 0;
    int a[3][3] = {{92,88,4},{6,10,36},{96,66,83}};
    int *b;
    b=&a[0][0];
    for(i=0; i< 9; i++){
      printf("%d\t", b[i]);
    }
    return 0;
 }

這是因為在 C/C++ 中,多維 arrays 連續存儲在 memory 中。 可以在這里找到一個很好的討論

首先,對於time function in srand((unsigned)time(NULL)); 你需要包括<time.h>

要將值存儲在一維數組中,您只需創建一個size = col * row的數組。 在下面的這個例子中,我分配了int指針來保存所有的值:

int * arr_1D = malloc(sizeof(int) * i * y);
    if (arr_1D == NULL)
        exit(-1);

完整的代碼(我剛剛添加了一些將 2D 轉換為 1D 的內容):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    printf("Enter the number of rows: ");
    int i; 
    scanf("%d", &i);

    printf("Enter the number of columns: ");
    int y; 
    scanf("%d", &y);

    int array[i][y];
    int rows, columns;
    int random;

    srand((unsigned)time(NULL));

    int * arr_1D = malloc(sizeof(int) * i * y);
    if (arr_1D == NULL)
        exit(-1);

    int count = 0;
    for(rows=0;rows<i;rows++)
        {
            for(columns=0;columns<y;columns++)
                {
                    random=rand()%100+1;

                    array[rows][columns] = random;
                    printf("%i\t",array[rows][columns]);
                    // The code for converting 2D to 1D array 
                    arr_1D[count++] =  array[rows][columns];
                }

            printf("\n");
        }

    for (int k = 0; k < count; ++k)
    {
        printf("%d ", arr_1D[k]);
    }

return 0;
}

結果:

Enter the number of rows: 4
Enter the number of columns: 3
15  6   60  
91  16  67  
61  72  86  
6   61  91  
15 6 60 91 16 67 61 72 86 6 61 91

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM