c++ - 指针错误导致的段错误(简单...)

标签 c++ arrays function pointers

我有一个返回指向 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/

相关文章:

r - R 中的速度优化

jquery - 为不同的 div 乘以 jquery 函数(一个函数很多 div)

C++ vector 范围构造函数

javascript - 使用Reduce和Filter JavaScript查找数组中数字的众数

C++ 如何使用views::split 打印单词?

javascript - 从数组中的 SQL 捕获 PHP 变量并输出到 JavaScript 变量

javascript - 我现在有多行字符串,我想打印包含特定子字符串的那些行

javascript - 我不知道如何修复我的成绩计算器功能

c++ - Pthread_mutex_lock 返回访问错误

c++ - 如何在if语句的括号内声明一个变量?