【发布时间】: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