我有指針返回到double數組的函數:分割故障(簡單...)
double * centerOfMass(System &system) {
long unsigned int size = system.atoms.size();
double x_mass_sum=0.0; double y_mass_sum=0.0; double z_mass_sum=0.0; double mass_sum=0.0;
for (int i=0; i<=size; i++) {
double atom_mass = system.atoms[i].m;
mass_sum += atom_mass;
x_mass_sum += system.atoms[i].pos["x"]*atom_mass;
y_mass_sum += system.atoms[i].pos["y"]*atom_mass;
z_mass_sum += system.atoms[i].pos["z"]*atom_mass;
}
double comx = x_mass_sum/mass_sum;
double comy = y_mass_sum/mass_sum;
double comz = z_mass_sum/mass_sum;
double* output = new double[3]; // <-------- here is output
output[0] = comx*1e10; // convert all to A for writing xyz
output[1] = comy*1e10;
output[2] = comz*1e10;
return output;
}
當我嘗試由陣列保存到變量來訪問輸出(在不同的功能),我得到一個分段錯誤的程序運行時(但它編譯罰款):
void writeXYZ(System &system, string filename, int step) {
ofstream myfile;
myfile.open (filename, ios_base::app);
long unsigned int size = system.atoms.size();
myfile << to_string(size) + "\nStep count: " + to_string(step) + "\n";
for (int i = 0; i < size; i++) {
myfile << system.atoms[i].name;
myfile << " ";
myfile << system.atoms[i].pos["x"]*1e10;
myfile << " ";
myfile << system.atoms[i].pos["y"]*1e10;
myfile << " ";
myfile << system.atoms[i].pos["z"]*1e10;
myfile << "\n";
}
// get center of mass
double* comfinal = new double[3]; // goes fine
comfinal = centerOfMass(system); // does NOT go fine..
myfile << "COM " << to_string(comfinal[0]) << " " << to_string(comfinal[1]) << " " << to_string(comfinal[2]) << "\n";
myfile.close();
}
運行程序產生正常功能,直到它試圖調用centerOfMass
。
我檢查了最可能的解決方案;我認爲我只是缺乏對C++中指針和範圍的理解。我在PHP中經驗豐富,因此明確地處理內存是有問題的。
太感謝您了
'對(INT I = 0; I <=大小;我++){'似乎不可思議。不應該是'for(int i = 0; i
songyuanyao
@songyuanyao拍當,謝謝。錯過了。謝謝你的眼睛。如果你發佈一個答案,我會接受:3 – khaverim
@khaverim好消息 - 你不必誤會指針和其範圍在C++中。你只是犯了一個簡單的錯誤,沒關係。 – synchronizer