我对c++的编码非常陌生,所以如果这个问题有一个非常简单的答案,我很抱歉。我试图创建一个从-1到1的随机数矩阵。下面是我使用的两个函数:
#include <iostream>
#include "matrix_fill_random.cpp"
using namespace std;
int main(int argc, int argv[]){
int n1, n2, n3;
if (argc != 4) {
cerr << "This program requires 3 argument!" <<endl;
return 1;
}
else{
n1 = argv[1];
n2 = argv[2];
n3 = argv[3];
double** a;
matrix_fill_random(n1, n2, a);
return 0;
}
}和
#include <iostream>
using namespace std;
int matrix_fill_random(int n1, int n2, double** a){
for (int i=0; i<n1; i++){
for (int j=0; j<n2; j++){
double num = rand() % 2 - 1;
a[i][j]=num;
}
}
return 0;
}最终,我试图创建两个矩阵,然后将它们相乘,以便n1、n2和n3表示两个矩阵的行和列,但这一点现在并不太重要。我认为错误可能在于我如何声明变量或将它们传递给其他函数,但我不完全确定。
我觉得如果我能理解创建一个矩阵的原理,那么它就会转化为我需要使用的其他功能。
发布于 2013-09-29 22:15:05
double** a;您没有为指针分配内存,所以每次使用operator []取消引用时都会得到未定义的行为。
您应该在传递a之前分配它一次.
double** a = new double*[n1];并再次在函数的for循环中:
for (int i = 0; i < n1; i++)
{
a[i] = new double[n2];
for (int j = 0; j < n2; j++)
{
double num = rand() % 2 - 1;
a[i][j] = num;
}
}但是,当您使用完指针后,不要忘记delete[]。您也应该delete在for循环中分配的其他指针。
当然,使用std::vector可以避免这一切。这是您的程序与标准图书馆:
std::vector<std::vector<double>> a(n1, std::vector<double>(n2));
int matrix_fill_random(std::vector<std::vector<double>> a)
{
for (int i = 0; i < a.size(); ++i)
{
for (int j = 0; j < a[i].size(); ++j)
{
double num = rand() % 2 - 1;
a[i][j] = num;
}
}
return 0;
}发布于 2013-09-29 22:16:28
为a分配内存。您还没有为. Chane语句double** a;分配内存
double** a = new double[n1];并按以下方式更改循环
for (int i = 0; i < n1; i++)
{
//Every row will be of size = number of columns.
a[i] = new double[n2];
for (int j = 0; j < n2; j++)
{
double num = rand() % 2 - 1;
a[i][j] = num;
}
} 发布于 2013-09-29 22:13:40
double** a;
matrix_fill_random(n1, n2, a);将未初始化的指针a传递给函数,该函数试图初始化二维数组的元素:
a[i][j]=num;它调用未定义的行为。最简单的解决方案是分配一个足够大的内存块来保存矩阵:
double* a = new double[rows * cols];
matrix_fill_random(n1, n2, a);
delete[] a;
a = NULL;
...
// accessing element a[i][j] in the function's body:
a[i*cols + j] = num;但是最合理的解决方案是使用std::vector而不是C风格的数组。
https://stackoverflow.com/questions/19083862
复制相似问题