0

我是 C++ 指针的新手,从指针获取值时遇到问题。

我有一个指针 verticesPosBegin ,它指向用于保存顶点位置的数组的开头。每个顶点存储为一个 3 分量浮点向量 (xyz)。

我需要从中获取每个顶点并访问其 x、y、z 值。

我是通过以下方式做到的:

NxVec3* positions = (NxVec3*)data.verticesPosBegin;

for(int i=0;i<nrVertices;i++)
{

  NxVec3* p1 = (NxVec3*)positions;
  printf("Vertex coordinates x: %d, y: %d, z: %d\n", p1->x, p1->y, p1->z);
  positions++;
}

(NxVec3 是一种由我使用的物理引擎定义的类型,它基本上是一种形式的结构(float x,float y,float z))

但这并没有让我得到坐标的值,而是地址,我猜,因为它们代表了非常大的数字。任何帮助将不胜感激。

4

3 回答 3

6

根据您的说法,p1->xp1->yp1->ztype float,对吗?如果是这样,您将不正确的格式字符串传递给 printf。该%d标志用于整数。你可能想要%f旗帜。您得到的巨大数字不是地址,而是浮点值,转换为双精度数,然后将它们的位模式解释为整数,尽管它在技术上是未定义的行为。

http://en.cppreference.com/w/cpp/io/c/fprintf

如果你使用 cout 代替,你不必担心这样的事情,因为它是类型安全的。

附言

停止施法。它只会隐藏编译时,并将它们转移到运行时错误,这要糟糕得多。

于 2013-05-19T17:45:08.523 回答
1
  • 如果您真的想使用指针(我建议仅用于练习目的)和
  • ifdata.verticesPosBegin指向一个连续的 Nx3 浮点数块
  • 如果 NxVec3 是只有三个数据成员的类/结构 float x, y, z;

以下应该有效:

NxVec3 *positions = (NxVec3*)data.verticesPosBegin, *p(positions);

for(unsigned int i=0;i<nrVertices;i++)
{
  cout << "Vertex coordinates ";
  cout << "x: " << p->x << ", ";
  cout << "y: " << p->y << ", ";
  cout << "z: " << p->z << endl;
  ++p;
}
于 2013-05-19T17:49:26.420 回答
0

如果我猜NxVec3对了,这里是定义,NxVec3,所以,根据头文件,以下应该可以工作:

NxVec3* positions = (NxVec3*)data.verticesPosBegin;

for(int i = 0;i < nrVertices; ++i)
{
    float *p = positions[i].get();
    cout << p[0] << ' ' << p[1] << ' ' << p[2] << endl;
}
于 2013-05-19T17:43:34.327 回答