我正在尝试开发一个代码,该代码部分地与文件中保存的矩阵相关。我在Windows 8中使用Eclispe luna + Cygwin。 这是我的代码:
A.cpp类
void A::Initialize(string toto){
string ligne;
lig = 0; // nbre des lignes
col=0;
int copienj[lig];
ifstream fichier_toto(toto.c_str(), ios::in);
if(fichier_toto.fail()){
cout << "Le fichier " << toto << " n'existe pas !" << endl;
}
ifstream fichier(toto.c_str(), ios::in);
if(!fichier.fail()) {
while(getline(fichier, ligne)){
lig++;
}
int kk=0;
int llm=ligne.length();
for(int y=0; y<llm;y++){
if(ligne[kk]==' '){
col++;
}
kk++;
}
col++;
int DLocal[lig-1][col];
string data1[lig*col];//on stocke les # variables dans un tableau
fichier.seekg(0, ios::beg);
if((int)fichier.tellg() != 0) {
fichier.clear();
fichier.seekg(0, ios::beg);
}
for(int i=0; i<(lig*col);i++){
fichier >> data1[i] ; /*on lit jusqu'à l'espace et on stocke ce qui est lu dans la variable indiquée */
}
// remplissage de D
int k=col;
for(int i=0; i<lig-1;i++){
for (int j =0; j<col;j++){
DLocal[i][j]=atof(data1[k+i+j].c_str());
}
k=k+col-1;
}
//on cherche D
D=&DLocal[0][0];
// nbre delignes dans notre matrice D
lig--;
m=col-2;
/******* on affiche DLocal *******************/
cout<<" D From class A"<<endl;
for(int i=0; i<lig;i++){
for (int j =0; j<col;j++){
cout<<DLocal[i][j]<<" ";
}
cout<<endl;
}
}
班级B.cpp
B::Function(){
A* dt=new A();
dt->Initialize("E:\\processing_Times_C\\prb3_4.txt");
D=dt->D;
lig=dt->lig;
col=dt->col;
n=dt->n;
m=dt->m;
nb_op=dt->nb_op;
nj=dt->nj;
cout<< "D: "<<endl;
int copie[lig][col];
for(int i=0; i<lig;i++){
for (int j =0; j<col;j++){
copie[i][j]=*(D+i*col+j);
}
}
cout<<" D From Class B:"<<endl;
for(int i=0; i<lig;i++){
for (int j =0; j<col;j++){
cout<<copie[i][j]<< " ";
}
cout<<endl;
}
}
通常我必须得到这个:
D from class A:
1 1 1 3 4 1
1 2 3 8 2 1
1 3 3 5 4 7
2 1 4 1 1 4
2 2 2 3 9 3
2 3 9 1 2 2
3 1 8 6 3 5
3 2 4 5 8 1
D from class B:
1 1 1 3 4 1
1 2 3 8 2 1
1 3 3 5 4 7
2 1 4 1 1 4
2 2 2 3 9 3
2 3 9 1 2 2
3 1 8 6 3 5
3 2 4 5 8 1
但我得到了这个:
D from class A:
1 1 1 3 4 1
1 2 3 8 2 1
1 3 3 5 4 7
2 1 4 1 1 4
2 2 2 3 9 3
2 3 9 1 2 2
3 1 8 6 3 5
3 2 4 5 8 1
D from class B:
2344128 0 2343792 0 24 0
8 0 2344160 0 -16338585 3
1 3 3 5 4 7
469600 6 469600 6 4 0
3 0 -2146642573 1 4 0
-16219983 3 9 1 2 2
3 1 8 6 2343360 0
-2146277029 1 4 5 8 1
你有想法解决这个问题吗? 谢谢
答案 0 :(得分:1)
您有未定义的行为。您定义了一个本地int数组DLocal
,它将位于堆栈中。从函数返回时,它将被销毁。您正在D
中存储指向该内存区域的指针,因此它可以包含此时恰好位于堆栈中的任何数据。