我是这个网站的新手,所以如果我以错误的方式提问,请原谅。
在我的编程类(class)中,我被要求编写一个函数,该函数将使用指针为我提供两个方阵 (3x3) 的乘积。
这是我写的代码:
//This function make a LxC matrix out of a double pointer
void matrixMake(double **a,int unsigned l,int unsigned c)
{
a=new double*[l];
for(int i=0;i<l;i++)
{
a[i]=new double[c];
}
}
//This function returns a random number between a and b
double randU(double a=0.0,double b=10.0)
{
double x=(double)(rand()/RAND_MAX);
return(a*x+b*(1-x));
}
//This is the function that seems to be a problem, this function creates a matrix and fills it with random numbers between 0 and 10.
double ** matrixGen()
{
double **matrix;
matrixMake(matrix,3,3);
for(int i=0;i<3;i++)
{
for(int n=0;n<3;n++)
{
matrix[i][n]=randU();
}
}
return(matrix);
}
它编译得很好,除了当我运行程序时,它给我一个难看的段错误。
我尝试调试它,当它运行 matrix[i][n]=randU();
行时它崩溃了。
它没有给你完整的代码,其余的与我的问题无关,似乎工作正常。
希望我的问题不是太愚蠢^^...提前致谢! :D
最佳答案
除了更正matrixMake
的签名:
void matrixMake(double**& a, unsigned l, unsigned c)
你还应该纠正这个:
double x=(double)(rand()/RAND_MAX);
// x always evaluates to zero
进入这个:
double x=((double)rand())/RAND_MAX);
关于c++ - 使用 2D 指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373365/