c++ - 使用 2D 指针时出错

标签 c++

我是这个网站的新手,所以如果我以错误的方式提问,请原谅。

在我的编程类(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/

相关文章:

c++ - 为什么不将 std::double_t 流式传输到 std::cout 给我小数位?

c++ - 从特征矩阵中删除行

c++ - SVN和SFTP与eclipse同步

python - 与 PyTorch 的 torch.no_grad 等效的 LibTorch 是什么?

c++ - 获得可整除整数的 10 的最大次方的高效算法

c++ - 根据其 RTSP appsrc 客户端控制 appsink 管道的状态

c++ - C++ 中是否有类似于 Java 中的弱引用的东西?

c++ - 是否可以制作非 POD 类型的流?

c# - 将 Arduino 校验和函数转换为 C#

c++ - 编写客户端和服务器,UDP