【发布时间】:2017-04-15 02:27:22
【问题描述】:
我正在根据输入文件创建一个动态数组,并且在 gdc 中没有任何有用信息的情况下被抛出一个分段错误错误。 在调试时,我尝试检查 Ntot 是否被正确读取,并以某种方式修复了错误。 如果我删除 cout(如示例中所示)然后错误返回,有人知道为什么吗?
#include <iostream>
#include <math.h>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main(){
double **number;
int i, Ntot;
ifstream input("initial_parameters.dat");
input >> Ntot;
//cout<<Ntot<<endl;
//uncomenting this removes the error
number = (double**)malloc(sizeof(double*) * (5));
for (int i = 1; i <= 5; i++)
number[i] = (double*)malloc(sizeof(double) * (Ntot));
number[1][1] = 1.;
cout<<number[1][1]<<endl;
number[2][1] = 2.;
cout<<number[2][1]<<endl;
number[3][1] = 3.;
cout<<number[3][1]<<endl;
number[4][1] = 4.;
cout<<number[4][1]<<endl;
number[5][1] = 5.;
cout<<number[5][1]<<endl;
return 0;
}
编辑:工作数组初始化是:
double** number = new double*[5];
for (int i = 0; i < 5; i++)
number[i] = new double[Ntot];
【问题讨论】:
-
为什么,哦为什么你在C++中使用
malloc? -
您有未定义的行为,因为写入分配的内存超出范围。在 c++ 中,索引从
0到size - 1。 -
数组的第一个元素在索引 0 处。访问
number[5]会导致未定义的行为。 -
还有
Ntot的值是多少?如果是<=1,你会怎么做? -
@UnholySheep Ntot 是一个正整数值,我使用的是 1000 atm