簡體   English   中英

2D陣列混淆(C程序)

[英]2D Array Confusion (C program)

我有一個2D數組,我們稱之為“A1”。

A1[rows][cols].

后來在我的程序中,我創建了另一個名為“A2”的2D數組,

A2[new_rows][new_cols]

A2比我的大A1 ...有沒有辦法為我設定A1同樣大小和內容A2

數組在C中是靜態的,所以遺憾的是,一旦定義數組,就無法更改數組的大小。 但是,您可以使用動態分配的數組來實現您所說的內容(盡管這與調整數組大小並不完全相同,因為在重新分配時,您將丟失對原始數組的引用)。 首先使用malloc創建兩個動態分配的數組A1A2 接下來,使用reallocA1重新分配為與A2相同的大小。 最后,將A2的內容復制到A1 這將有效地“調整” A1的大小與A2大小相同,其內容與A2相同。 這是一些示例代碼(您可以使用適合您的任何填充方法,我只使用填充):

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

int **make2DArray(int rows, int cols);
void populate2DArray(int **array, int rows, int cols);
void print2DArray(int **array, int rows, int cols);

int main(int argc, char **argv)
{
  int i, j;
  int rows = 2, cols = 3;
  int newRows = 4, newCols = 7;

  // Create two dynamic arrays.
  int **A1 = make2DArray(rows, cols);
  int **A2 = make2DArray(newRows, newCols);

  // Populate the dynamic arrays (however you like).
  populate2DArray(A1, rows, cols);
  populate2DArray(A2, newRows, newCols);

  // Print original arrays.
  printf("A1 (before):\n");
  print2DArray(A1, rows, cols);
  printf("\nA2 (before):\n");
  print2DArray(A2, newRows, newCols);

  // Reallocate A1 to be same size as A2.
  int **temp = realloc(A1, sizeof(int *) * newRows);
  if (temp)
  {
    A1 = temp;
    int *tempRow;
    for (i = 0; i < newRows; i++)
    {
      tempRow = realloc(A1[i], sizeof(int) * newCols);
      if (tempRow)
      {
        A1[i] = tempRow;
      }
    }
  }

  // Copy contents of A2 to A1.
  for (i = 0; i < newRows; i++)
  {
    for (j = 0; j < newCols; j++)
    {
      A1[i][j] = A2[i][j];
    }
  }

  // Print resized A1 (should be same as A2).
  printf("\nA1 (after):\n");
  print2DArray(A1, newRows, newCols);
  printf("\nA2 (after):\n");
  print2DArray(A2, newRows, newCols);
}

int **make2DArray(int rows, int cols) {
  // Dynamically allocate a 2D array.
  int **array = malloc(sizeof(int *) * rows);
  if (array)
  {
    for (int i = 0; i < rows; i++)
    {
      array[i] = malloc(sizeof(int) * cols);
    }
  }

  return array;
}

void populate2DArray(int **array, int rows, int cols) {
  // Populate a 2D array (whatever is appropriate).
  int i, j;
  for (i = 0; i < rows; i++)
  {
    for (j = 0; j < cols; j++)
    {
      array[i][j] = i + j;
    }
  }
}

void print2DArray(int **array, int rows, int cols)
{
  // Print a 2D array to the terminal.
  int i, j;
  for (i = 0; i < rows; i++)
  {
    for (j = 0; j < cols; j++)
    {
      printf("%d ", array[i][j]);
    }
    printf("\n");
  }
}

以下代碼的輸出將是:

A1 (before):
0 1 2 
1 2 3 

A2 (before):
0 1 2 3 4 5 6 
1 2 3 4 5 6 7 
2 3 4 5 6 7 8 
3 4 5 6 7 8 9 

A1 (after):
0 1 2 3 4 5 6 
1 2 3 4 5 6 7 
2 3 4 5 6 7 8 
3 4 5 6 7 8 9 

A2 (after):
0 1 2 3 4 5 6 
1 2 3 4 5 6 7 
2 3 4 5 6 7 8 
3 4 5 6 7 8 9 

暫無
暫無

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

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