指针算术和导航 malloc 数组

发布于 2024-08-02 01:21:28 字数 755 浏览 3 评论 0原文

好的,我正在为 iPhone 开发 OpenGL ES 应用程序,并且遇到了一个有趣的问题。

我有一个函数,可以根据细节级别和球面坐标范围来​​计算球体的顶点、法线和纹理坐标。

最初,将顶点存储在数组中看起来像这样:

//After I figure out the size of the vertices:
GLfloat* vertices = (GLfloat *) (malloc(sizeof(GLfloat) * arraySize)));

//Later on when I'm computing vertices...
GLfloat* vertPosition = vertices;

vertPosition[0] = px;
vertPosition[1] = py;
vertPosition[2] = pz;
vertPosition += 3;

事实证明这是一场灾难。 我最终得到了类似 AT&T 标志的东西。 :-) 我发现添加一个计数器并使用它来索引数组修复了所有问题:

vertPosition[(vertexCount * 3) + 0] = px;
vertPosition[(vertexCount * 3) + 1] = py;
vertPosition[(vertexCount * 3) + 2] = pz;
vertexCount++;

我的问题是:使用临时指针并将其向前移动会发生什么情况? 我现在所得到的是否同样有效,或者指针算术会更好吗?

Okay, so I'm working on an OpenGL ES application for the iPhone, and I ran into an interesting issue.

I have a function that computes the vertices, normals, and texture coordinates of a sphere dependent upon a detail level and a range of spherical coordinates.

Originally, storing a vertex in an array looked something like this:

//After I figure out the size of the vertices:
GLfloat* vertices = (GLfloat *) (malloc(sizeof(GLfloat) * arraySize)));

//Later on when I'm computing vertices...
GLfloat* vertPosition = vertices;

vertPosition[0] = px;
vertPosition[1] = py;
vertPosition[2] = pz;
vertPosition += 3;

This turned out to be a disaster. I ended up with something like the AT&T logo. :-) A bit more work I discovered adding a counter and using that to index the array fixed everything:

vertPosition[(vertexCount * 3) + 0] = px;
vertPosition[(vertexCount * 3) + 1] = py;
vertPosition[(vertexCount * 3) + 2] = pz;
vertexCount++;

My questions are: What happened with using a temporary pointer and moving it ahead? Is what I've got now just as efficient, or would the pointer arithmetic be better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时间海 2024-08-09 01:21:28

从你发布的内容来看,应该是一模一样的。 我能想到的第一件事是该错误位于代码中的其他位置。

我唯一能想到的另一件事是,如果不是采用顶点数组,而是实际上采用坐标数组,并且坐标中可能有填充,那么这也可以解释其中的差异。

From the looks of what you posted it should be exactly the same. The first thing that I can think of is that the bug is somewhere else in your code.

The only other thing that I can think of is if instead of taking an array of verts, it might actually takes an array of coords and the coords might have padding in them then that could also explain the difference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文