【问题标题】:How to allocate the memory for matrices(2DArray) dynamically in which rows and columns are also allocated dynamically?如何为矩阵(2DArray)动态分配内存,其中行和列也是动态分配的?
【发布时间】:2021-07-18 21:41:48
【问题描述】:

在我的代码中,它只为一个矩阵分配内存。当我在这里尝试为两个矩阵分配内存时,只分配了两列内存,没有其他机会为第二个矩阵分配内存。

这是我的代码

    void 2DArray()
     {
         int noOfRows, noOfColumns, noOfMatrices;
         printf("\n\n ENTER THE NUMBER OF  MATRICES YOU WANT TO ADD : ");
         scanf("%d",&noOfMatrices);
         int **2DArray = (int**)malloc((noOfMatrices * sizeof(int)));

         for(int i = 0; i < noOfMatrices; i++)
          {
                  2DArray[i] = (int*)malloc((sizeof(int) * noOfRows));
          }
     }

请帮帮我!

【问题讨论】:

  • 不是二维数组。它是指针数组!!
  • @Nagrocks Naa - noOfRowsnoOfColumns 未初始化 - 你必须决定它们的值来自哪里。
  • 为什么要使用 C 和 C++ 进行标记?它们是两种完全不同的语言。
  • 请以tour 开头并阅读How to Ask。此外,描述您的实际问题(观察、期望等)。最后,如上所述,通过您应用的标签的描述,两者通常是互斥的。

标签: c++ c


【解决方案1】:

在 C 中:

void *allocate2DintArray(size_t cols, size_t rows)
{
    int (*arr)[rows][cols];
    return malloc(sizeof(*arr));
}

在 C++ 中(一种可能的方式)

vector <vector <int>> Matrix(rows, vector <int>(cols, 0));

【讨论】:

  • sizeof(*arr) 是否是 UB 存在争议。见stackoverflow.com/questions/32985424/…
  • @tstanisl 编译器都知道这样做正确 - 这意味着他们的开发人员以与 SO 大师不同的方式解释它。对我来说,编译器开发者的解释比 SO 更重要。
猜你喜欢
  • 2021-12-19
  • 1970-01-01
  • 2010-11-27
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
相关资源
最近更新 更多