2D阵列混淆(C程序)

时间:2017-03-03 16:20:32

标签: c arrays memory multidimensional-array

我有一个2D数组,我们称之为“A1”。

A1[rows][cols].

稍后在我的程序中,我创建了另一个名为“A2”的2D数组,

A2[new_rows][new_cols]

A2大于A1 ...我有什么方法可以将A1设置为相同大小&内容A2

1 个答案:

答案 0 :(得分:0)

数组中的数组是静态的,所以很遗憾,一旦定义了数组,就无法更改数组的大小。但是,您可以使用动态分配的数组来实现您所说的内容(尽管这与调整数组大小并不完全相同,因为在重新分配时,您将丢失对原始数组的引用)。首先使用A1创建两个动态分配的数组A2malloc。接下来,使用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