c - 非静态变量的累积返回值?

标签 c

我编写的用于计算一组 3D 点的平均点的函数遇到了意外行为。

static inline Point3d
average_vertex_position( Vertex vertices[], int nPoints )
{
  Point3d average = { 0.0, 0.0, 0.0 }; // Must be there to avoid accumulation
  Point3d point;
  int i;

  for ( i = 0; i < nPoints; i++ )
  {
    point = vertices[i].position;
    average.x += point.x;
    average.y += point.y;
    average.z += point.z;
  }

  average.x /= (double) nPoints;
  average.y /= (double) nPoints;
  average.z /= (double) nPoints;

  return average;
}



// ...
Point3d average;
// ...
for ( j = i; j < nVertices; j++ )
{
  // ...
  average = average_vertex_position( vertices, nVertices );
  // ...
}

对于每次迭代,average_vertex_position 的返回值都会累积,除非我明确添加初始化 Point3d average = { 0.0, 0.0, 0.0 };

如果之前的返回值是 Point3d( 10, 0, 20 ) 而下一次运行应该返回 Point3d( 20, 10, 0 ) 它会改为返回累积结果 Point3d( 30, 10, 20 )

最初我只有 Point3d average; 假设所有成员值(double 值)都将初始化为 0.0。我还假设 average 会在每次调用之间处于这个初始状态。我不明白为什么我需要显式初始化它?

我删除了我认为不相关的代码 - 但我可能是错的,在这种情况下,如果它没有包含足够的信息,我会进行更新。

最佳答案

这对于 auto 变量是正常的 - 如果没有明确说明,它们不会被初始化为 0。

旧值被重用纯属巧合,因为中间没有任何其他函数调用。如果你有它们,给定堆栈位置的内存将被覆盖并且你的值不同。

关于c - 非静态变量的累积返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9667319/

相关文章:

c - 用于计算时间流逝的独立于操作系统的 C 库?

无法按字母顺序(排序)字符串吗?

c - 系统调用 - 内核使用的函数

C:替换转义字符 esp '\\'

c++ - 如何在 C/C++ 中分配垃圾值

c++ - 当 Py_initialize 失败时如何捕获并处理 fatal error ?

file - 通过添加竞争条件来停止竞争条件?

c - 使用 malloc 为结构体分配内存

c - 用 C 语言从推文中获取主题标签

c++ - arm和x86架构下的c/c++语言有什么区别