C++ for循环中复用数组变量xi[3]是否会引发问题?(LAMMPS开发)
LAMMPS中复用临时数组xi[3]的写法问题解答
你这种在循环内复用临时数组xi[3]的写法不存在语法或逻辑上的未知问题,具体分析如下:
- 逻辑层面无问题:在3D分支的循环中,你先给
xi赋值随机数并完成torque的累加操作,之后才覆盖xi的值用于力矩相关计算。两次使用的xi值相互独立——第一次的随机值已经完成了它的作用,后续覆盖不会影响之前的计算结果,逻辑链条清晰。 - 语法层面合规:
xi是栈上声明的固定大小数组,循环内的赋值操作只是覆盖栈内存中的旧值,这是C++中栈变量的常规用法,不会引发内存泄漏、野指针这类问题。同时你在所有用到xi的分支里都明确完成了赋值(2D分支仅用xi[2]且已赋值,3D分支所有元素都先赋值再使用),避免了未初始化内存导致的未定义行为。 - 可读性优化建议:如果想让代码更直观,可将两次使用的临时值拆分到两个独立数组中,比如用
rand_xi[3]存随机值,torque_xi[3]存力矩计算值。这只是代码风格优化,并非当前写法的错误。
你的代码如下:
double **angmom = atom->angmom; double **omega = atom->omega; double **torque = atom->torque; int *mask = atom->mask; int *type = atom->type; int nlocal = atom->nlocal; double *moment = atom->moment; double xi[3]; if (dimension == 2) { for (int i = 0; i < nlocal; i++){ if (mask[i] & groupbit) { xi[2] = sqdr*(random->uniform() - 0.5); torque[i][2] += xi[2] - eta*angmom[i][2]; } } } else { for (int i = 0; i < nlocal; i++){ if (mask[i] & groupbit) { xi[0] = sqdr*(random->uniform() - 0.5); //One use of chi xi[1] = sqdr*(random->uniform() - 0.5); xi[2] = sqdr*(random->uniform() - 0.5); torque[i][0] += xi[0]; torque[i][1] += xi[1]; torque[i][2] += xi[2]; xi[0] = angmom[i][1]*omega[i][2] - angmom[i][2]*omega[i][1]; //re-use chi xi[1] = angmom[i][2]*omega[i][0] - angmom[i][0]*omega[i][2]; xi[2] = angmom[i][0]*omega[i][1] - angmom[i][1]*omega[i][0]; torque[i][0] += -eta*xi[0]; torque[i][1] += -eta*xi[1]; torque[i][2] += -eta*xi[2]; } } }
内容的提问来源于stack exchange,提问作者Physics_iyer
相关产品推荐
相关产品推荐

