在C语言中动态声明各种2D数组

在C语言中动态声明各种2D数组,c,arrays,C,Arrays,我必须声明三个C大小为Rx3的2D数组,称为array1、array2和sum int main() { int row = 0; printf("Enter the no. of rows:"); scanf("%d", &row); printf("MyArray[%d][3]", row); int ** array1; array1 = (int**)malloc(4 * row); int rep1; for (rep1 = 0; rep1

我必须声明三个C大小为Rx3的2D数组,称为array1、array2和sum

int main() 
{
  int row = 0;
  printf("Enter the no. of rows:");
  scanf("%d", &row);
  printf("MyArray[%d][3]", row);

  int ** array1;
  array1 = (int**)malloc(4 * row);
  int rep1;
  for (rep1 = 0; rep1 <= row; rep1++) 
  {
    array1[rep1] = (int*)malloc(3 * 4);
  }

  int ** array2;
  array2 = (int**)malloc(4 * row);
  int rep2;
  for(rep2 = 0; rep2 <= row; rep2++)
  {
    array2[rep2] = (int**)malloc(3 * 4);    
  }
}
intmain()
{
int行=0;
printf(“输入行数:”);
scanf(“%d”行和第行);
printf(“MyArray[%d][3]”,第行);
国际**阵列1;
数组1=(int**)malloc(4*行);
杰出代表1;

对于(rep1=0;rep1,此代码在GCC编译器中运行良好

#include <stdio.h>
#include <stdlib.h>
int main()
{
        int row=0;
        printf("Enter the no. of rows:");
        scanf("%d", &row);

        printf("MyArray[%d][3]",row);
        int **array1 = (int**)malloc(sizeof(int*)*row);
        int rep1;

        for (rep1 = 0; rep1 <= row; rep1++)
        {
                array1[rep1] = (int*)malloc(3*sizeof(int));
        }

        int ** array2;

        array2 = (int**)malloc(sizeof(int*)*row);
        int rep2;

        for(rep2 = 0; rep2 <= row; rep2++)
        {
                array2[rep2] = (int*)malloc(3*sizeof(int));
        }
}
#包括
#包括
int main()
{
int行=0;
printf(“输入行数:”);
scanf(“%d”行和第行);
printf(“MyArray[%d][3]”,第行);
int**array1=(int**)malloc(sizeof(int*)*行);
杰出代表1;
对于(rep1=0;rep1
这里的
4
是什么?是
sizeof(int)
硬编码还是列数

要为具有固定宽度的二维阵列保留空间,可以使用:

#define COLS 4

int (*arr)[COLS]; /* A pointer to an array of n int's */
size_t nrows = user_input();

arr = malloc(sizeof(*arr) * nrows);
如果事先不知道列数,可以使用(自C99起):

如何添加第三个数组

或者,如果您喜欢大块头:

size_t ncols = user_input();    
int (*arr)[ncols];
size_t nrows = user_input();

arr = malloc(sizeof(*arr) * nrows * 3);

int (*arr1)[ncols] = arr;
int (*arr2)[ncols] = arr + rows;
int (*arr3)[ncols] = arr + rows * 2;

这样,一个简单的
free(arr);
就足够了。

4是整数的大小如果不这样做,请始终使用
sizeof(int)
以及如何添加这两个数组?简单提示:永远不要在C中使用2D数组,尤其是对于堆分配的数据。始终使用一维数组,可能是,并定义
静态内联
函数来访问和修改它们以将其视为矩阵。换句话说,让矩阵抽象数据类型并正确实现它。
size_t ncols = user_input();    
int (*arr)[ncols]; /* VLA */
size_t nrows = user_input();

arr = malloc(sizeof(*arr) * nrows);
size_t ncols = user_input();    
int (*arr1)[ncols];
int (*arr2)[ncols];
int (*arr3)[ncols];
size_t nrows = user_input();

arr1 = malloc(sizeof(*arr1) * nrows);
arr2 = malloc(sizeof(*arr2) * nrows);
arr3 = malloc(sizeof(*arr3) * nrows);
size_t ncols = user_input();    
int (*arr)[ncols];
size_t nrows = user_input();

arr = malloc(sizeof(*arr) * nrows * 3);

int (*arr1)[ncols] = arr;
int (*arr2)[ncols] = arr + rows;
int (*arr3)[ncols] = arr + rows * 2;