简体   繁体   中英

A pointer to pointer in a struct C/ObjC

 typedef struct { float Position[3]; float Color[4]; float VertexNormal[3]; } Vertex; typedef struct WingedEdge{ struct WingedEdge* sym; struct WingedEdge* next; struct WingedEdge* prev; Vertex** vertex; GLushort** indexPointer; } WingedEdge; Vertex* vertices; GLushort* indices; struct WingedEdge* wingedEdges; int numberOfVertices; //initialized elsewhere int numberOfIndices; //initialized elsewhere,this is multiplied by three since I am not using a struct for the indices vertices = (Vertex *) malloc(numberOfVertices * sizeof(Vertex)); indices = (GLushort *) malloc(numberOfIndices * sizeof(GLushort) * 3); wingedEdges = (struct WingedEdge*)malloc(sizeof(struct WingedEdge)*numberOfIndices*3); for (int i = 0; i < numberOfIndices*3; i+=3) { wingedEdges[i].indexPointer = (&indices+i); wingedEdges[i+1].indexPointer = (&indices+i); wingedEdges[i+2].indexPointer = (&indices+i); wingedEdges[i].vertex = (&vertices+indices[i]); wingedEdges[i+1].vertex = (&vertices+indices[i+1]); wingedEdges[i+2].vertex = (&vertices+indices[i+2]); NSLog(@"%hu %hu %hu", *(indices+i),*(indices+i+1),indices[i+2]); NSLog(@"%f %f %f", (vertices+indices[i])->Position[0], (vertices+indices[i])->Position[1], (vertices+indices[i])->Position[2]); NSLog(@"%f %f %f", (vertices+indices[i+1])->Position[0], (vertices+indices[i+1])->Position[1], (vertices+indices[i+1])->Position[2]); NSLog(@"%f %f %f", (vertices+indices[i+2])->Position[0], (vertices+indices[i+2])->Position[1], (vertices+indices[i+2])->Position[2]); NSLog(@"%hu", **(wingedEdges[i].indexPointer)); } 

Tried looking at a few other problems with pointers and structs but I did not find anything. I am getting an error with the last NSLog call. Everything thing in the NSLog calls with indices and vertices is correct so it looks like it might be a simple syntax error or pointer issue. Also, how would I increment the pointer that indexPointer points to? Since indexPointer points to a indices pointer, then I want to access indices+1 and indices+2 as well through indexPointer.

(&indices+i) doesn't point to any memory you have allocated.

What will work is to change the indexPointer and vertex to single pointers and then

wingedEdges[i].indexPointer = &indices[i];
wingedEdges[i].vertex = &vertices[indices[i]];

Then *(wingedEdges[i].indexPointer) is the same as indices[i] and wingedEdges[i].vertex->Position[0] is the same as vertices[indices[i]].Position[0]. However, you will not get the automatic updating that you want (see my comments for more details). I recommend a simple inline function:

inline *Vertex vertex(WingedEdge* e) 
{
    return &vertices[*(e->indexPointer)];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM