在函数C ++中分配内存2D数组 [英] Allocate memory 2d array in function C++

查看:56
本文介绍了在函数C ++中分配内存2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为C ++中的函数内部的2D数组动态分配内存.除了使用malloc和dealloc编写它之外,已经提出了一个完全像这样的问题,所以我想知道您是否可以帮助我将其转换为使用new和delete.这是另一个问题:

I'm trying to dynamically allocate memory for a 2D array inside a function in C++. A question exactly like this has been asked except that it is written using malloc and dealloc, so I was wondering if you could help me convert it to use new and delete. Here is the other question:

在函数C中分配内存2d数组

我尝试将其更改为以下代码,但出现错误.

I tried changing it to the following code, but I'm getting errors.

void assign_memory_for_board(int ROWS, int COLS, int *** board) {
   *board = new int**[ROWS];
   for (int i = 0; i < ROWS; i++) {
       (*board)[i] = new int*[COLS];
   }
}

这是使用malloc和dealloc的答案:

Here is the answer that worked using malloc and dealloc:

void allocate_mem(int*** arr, int n, int m)
{
   *arr = (int**)malloc(n*sizeof(int*));
   for(int i=0; i<n; i++)
      (*arr)[i] = (int*)malloc(m*sizeof(int));
} 

谢谢!

推荐答案

您还有多余的星星.该功能应该是

You have extra stars. The function should be

void assign_memory_for_board(int ROWS, int COLS, int *** board) {
   *board = new int*[ROWS];
   for (int i = 0; i < ROWS; i++) {
       (*board)[i] = new int[COLS];
   }
}

这篇关于在函数C ++中分配内存2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆