1

有没有更快的方法将以下数据转换为 ac 样式指针数组?

GLfloat verticalLines [] = {
0.59, 0.66, 0.0,    
0.59, -0.14, 0.0
}

我目前的方法是使用以下方法手动迭代数据:

-(GLfloat *)updateLineVertices{

int totalVertices = 6;
GLfloat *lineVertices =  (GLfloat *)malloc(sizeof(GLfloat) * (totalVertices));

for (int i = 0; i<totalVertices; i++) {
    lineVertices[i] = verticalLines[i];
}

return lineVertices;
}

一些额外的信息。最终,我将需要一种易于操作的格式的数据,例如:

-(void)scaleLineAnimation{
GLfloat *lineVertices = [self updateLineVertices];
for (int i = 0; i<totalVertices; i+=3) {
     lineVertices[i+1] += 0.5; //scale y axis
}
}
4

2 回答 2

1

It depends on if verticalLines is going to stick around or not. If it's defined like it is above and it's not going to change, you can forgo the whole malloc and just point lineVertices to it.

linesVertices = &verticalLines[0]

if verticalLines is going to change, you probably want your own copy, so you've got no choice but to copy the actual data from one part of memory to another as you are doing, that being said, this might be a bit more elegant

for (int i = 0; i<totalVertices; i++){
    lineVertices[i] = verticalLines[i];
}

or the preferred method is probably to use memcopy(), here is some working code

//MemcopyTest.c
#include <cstdlib>
#include <stdio.h>
#include <string.h>

int main(){
   float a[] = {1.0,2.0,3.0};     //Original Array

   int size = sizeof(float)*3;      
   float *b = (float*)malloc(size); //Allocate New Array
   memcpy(b, a, size);              //Copy Data

   for(int i = 0; i<3; i++){
      printf("%f\n", b[i]);
   }
   free(b);
}
于 2012-10-12T19:58:09.660 回答
0

直接使用有什么问题verticalLines?任何类型T ident[n]都可以隐式转换为T* ident就好像您编写了&ident[0]. 如果你真的想明确,你可以直接写&ident[0]

于 2012-10-12T20:05:19.573 回答