c++ - 访问双指针导致段错误

标签 c++ pointers segmentation-fault

我正在为 QM 中的特征值问题编写 Jacobis 方法,我刚刚开始使用 c++,我想使用双指针构造矩阵,但涉及的物理问题需要大量代码。

我不想让我的 main() 乱七八糟的行(其他人将不得不阅读这段代码..)所以想把问题分解成子函数。我做了一个函数,它接受一个双指针并返回一个矩阵,但为什么我不能在函数外访问它?当我尝试时,我的代码段错误(在下面标记)。如何在 main() 之外构建矩阵,同时仍然能够在 main() 中访问它?

enter code her    enter code here
int i, j, k;  


//== BEGIN MAIN ==//
int main ()
{
  //Constants and variables          
  double **A;
  double epsilon = pow((double)10, double(-8)); //The convergence limit for jacobis   method
  int N          = 10;                          //Dimension of matrix
  char test[] =  "test";
  cout <<"The inner matrix function:"<<endl;
  makematrix(N, A);
  cout<<endl<<"The outer matrix function:"<<endl;
  //This part segfaults
  for(i=0; i<N; i++)
  {
  cout<<endl;
  for(j=0; j<N; j++)
{
  cout<<A[i][j]<<" ";
}
 }
return 0;
 }
 //== END MAIN ==//



//==Begin function definitions==//
void makematrix(int N, double **A)
{
   //Function for initializing our tridiagonal matrices for jacobis method
    A = new double*[N];
for(i=0; i<N; i++)
{
  A[i] = new double[N];
}
 for(i=0; i<N; i++)
{
  for(j=0; j<N; j++)
{
  A[i][j] = 0;
   }
     }
    //Prints the matrix declared here
    for(i=0; i<N; i++)
     {
       cout<<endl;
       for(j=0; j<N; j++)
    {
      cout<<A[i][j]<<" ";
    }
    }
 cout <<endl;
 return;
}

最佳答案

归还:

double** makematrix(int N) {
    double **A = new double*[N];
    ...
    return A;
}

主要...

double **A = makematrix(N);

关于c++ - 访问双指针导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7443760/

相关文章:

c++ - 如何在 3D 点上绘制文本?

你能从 C 中的 void * 打印值吗

c - 为二维数组分配内存时出现段错误

C 段错误 - 读者和作者

php - 为 php 扩展学习 C 或 C++

c++ - 在一个线程上删除具有数百万个字符串的大型 HashMap 会影响另一个线程的性能

c++ - 使用带 nvcc 和 CUSP 的 IFORT 的未解析引用

c - C 中的二叉搜索树出现奇怪的故障

c++ - 重新分配指针时出现段错误

python - 当使用 noexec 挂载/tmp 时,为什么在 Python 中出现段错误?