【问题标题】:Pass a 2d array pointer to a function and allocate memory inside the function将二维数组指针传递给函数并在函数内部分配内存
【发布时间】:2016-02-09 11:48:48
【问题描述】:

我有以下代码,其中我将一个二维动态数组传递给一个函数。该函数必须为数组分配内存并在其中插入值。

当我通过指针传递时,我将指针作为指向二维数组的指针接收。但是,当我尝试为其分配内存时出现错误。

void generateMatrix(int ***Matrix, int rows, int cols, int rank){

**Matrix = new int* [rows];
for(int rowIndex=0; rowIndex<rows; rowIndex++)
    *Matrix[rowIndex] = new int[cols];

srand(time(NULL) + rank);

for(int rowIndex=0; rowIndex<rows; rowIndex++)
     for(int colIndex=0; colIndex<cols; colIndex++)
        *Matrix[rowIndex][colIndex]=rand();
}


int main(int argc, char** argv){

int rank, procSize;
int matSize;
int **Matrix = NULL;

matSize = atoi(argv[1]);

MPI_Init(&argc, &argv);
MPI_Comm globalComm = MPI_COMM_WORLD;

MPI_Comm_rank(globalComm,&rank);
MPI_Comm_size(globalComm, &procSize);

std::cout<<"The number of processes are"<<procSize<<std::endl;
std::cout<<"The rank of the process is "<<rank<<std::endl;

std::cout<<"The size of the matrix is "<<matSize;

//1D-row agglomeration each process is going to store a set of continguous rows
int localRows = matSize/procSize;

int *v;
gen(&v);

generateMatrix(&Matrix, localRows, matSize, rank);


MPI_Finalize();
return 0;
}

我收到错误:无法在 **Matrix = new int* [rows] 行的赋值中将“int**”转换为“int*”。

具体应该怎么做? (将二维数组指针传递给分配内存和设置值的函数)

【问题讨论】:

  • 参数中有 3 颗星,但尝试写入时只使用 2 颗星。
  • 这真是一个可怕的想法,使用矢量
  • *Matrix[rowIndex][colIndex] 应该是 (*Matrix)[rowIndex][colIndex]。与*Matrix[rowIndex] 相同
  • 只调用一次srand

标签: c++ pointers memory-management segmentation-fault dynamic-arrays


【解决方案1】:

这样做:

*Matrix = new int* [rows];

解释:

三重指针包含双指针的地址 并且实际上你想为 double 创建数组。

***Matrix (in generateMatrix fun) 是 **Matrix (from main) 的地址

(在 generateMatrix 中玩) *矩阵是**矩阵(来自主)

考虑一下,如果我们在 main 中这样做:

int **Matrix;
Matrix = new int *[row];

所以我们使用 & 将 Matrix 按地址传送到另一个有趣的地方。

希望我的解释有帮助。

【讨论】:

  • 请在您的回答中添加一些解释。
  • 查看答案。添加一些解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2016-04-27
相关资源
最近更新 更多