我正在尝试迭代地在指针指针中存储一个二维数组。我用随机高斯值填充它,但这不是重要的部分。我尝试填充A
指向的数组,但得到“错误的访问代码”错误。我如何正确填充数组/指针?谢谢。
int main(){
int N = 100;
double **A[N][N];
for(int i = 0; i< N; i++){
for(int j =0; j < N; j++){
random_device rd;
default_random_engine generator;
generator.seed( rd() );
normal_distribution<double> distribution(0.0,1.0);
**A[i][j] = distribution(generator); // error here, bad access code 1
}
}
答案 0 :(得分:2)
首先,将double **A[N][N];
更改为double **A;
。你想要一个双指针,而不是双指针矩阵。然后,您必须像这样分配内存:A=new double*[N];
然后for(i=0;i<N;i++) A[i]=new double[n];
然后一切都会正常工作。您将以正常方式访问矩阵的元素A[i][j]
,而不是**A[i][j]
!
此示例代码将使您熟悉以下概念:
#include <iostream>
int main() {
int n=100;
double **a;
a=new double*[n];
for(int i=0;i<n;i++) a[i]=new double[n];
a[1][2]=3;
std::cout<<a[1][2];
for(int i=0;i<n;i++) delete a[i];
delete[] a;
return 0;
}
答案 1 :(得分:2)
您不能使用非const整数声明静态数组。
您正在声明一个指针数组,但指针并未指向任何有效内存,这就是您遇到内存错误的原因。
请改为尝试:
const int N = 100;
double A[N][N];
random_device rd;
default_random_engine generator;
generator.seed( rd() );
normal_distribution<double> distribution(0.0,1.0);
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
A[i][j] = distribution(generator);
}
}
或者,在堆上而不是堆栈上分配数组(然后你可以使用非const int作为维度):
int N = 100;
double **A = new double*[N];
for(int i = 0; i < N; ++i) {
A[i] = new double[N];
}
random_device rd;
default_random_engine generator;
generator.seed( rd() );
normal_distribution<double> distribution(0.0,1.0);
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
A[i][j] = distribution(generator);
}
}
...
for(int i = 0; i < N; ++i) {
delete[] A[i];
}
delete[] A;
或者这个:
int N = 100;
double *A = new double[N*N];
random_device rd;
default_random_engine generator;
generator.seed( rd() );
normal_distribution<double> distribution(0.0,1.0);
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
A[(i*N)+j] = distribution(generator);
}
}
...
delete[] A;
话虽如此,最好手动使用std::vector
代替new[]
:
int N = 100;
std::vector<std::vector<double> > A(N);
for(int i = 0; i< N; i++) {
A[i].resize(N);
}
random_device rd;
default_random_engine generator;
generator.seed( rd() );
normal_distribution<double> distribution(0.0,1.0);
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
A[i][j] = distribution(generator);
}
}
或者:
int N = 100;
std::vector<double> A(N*N);
random_device rd;
default_random_engine generator;
generator.seed( rd() );
normal_distribution<double> distribution(0.0,1.0);
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
A[(i*N)+j] = distribution(generator);
}
}
答案 2 :(得分:1)
错误在于:
**A[i][j] = distribution(generator);
A[i][j]
存储double**
类型的值。因此,您需要先将随机值存储在有效地址中,然后将其存储在A
。
/*Assign a new double* pointer to A[i][j]*/
A[i][j] = new double*;
/*Assign a new double pointer which is addressed by A[i][j]*/
*A[i][j] = new double;
/*Assign value to **A[i][j] */
**A[i][j] = distribution(generator);