我有一个返回指向 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 方面经验丰富,因此显式处理内存是有问题的。
谢谢你
最佳答案
我不确定 system.atoms
的类型。如果它是像 std::vector
这样的 STL 容器,则函数 centerOfMass
中的 for
循环的条件部分是错误的。
long unsigned int size = system.atoms.size();
for (int i=0; i<=size; i++) {
应该是
long unsigned int size = system.atoms.size();
for (int i=0; i<size; i++) {
PS1:你可以使用Range-based for loop (since C++11)避免此类问题。
PS2:您没有删除[]
动态分配的数组;考虑使用 std::vector , std::array , 或 std::unique_ptr相反,它们旨在帮助您避免此类问题。
关于c++ - 指针错误导致的段错误(简单...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41775314/