gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:57:44 26 4
gpt4 key购买 nike

我正在为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com