Neu definition

Started by
5 comments, last by Ethan 22 years, 2 months ago
Hi. Ich will einen Vertex-punkt neu definieren, aber ohne die daten zu verlieren. Bei meinem code ist das problem, das ich die Variable vVertex nicht mehr löschen kann. Kann mir jemand helfen? struct VERTEX{ float x; float y; float z; float tu; float tv; }; VERTEX *vVertex; int nVertexCount; // Fügt einen neuen Index zu einem Objekt hinzu void AddIndexToVERTEX(int nIndex) { if (nIndex==0) { vVertex = new VERTEX[0]; nVertexCount = 1; } else { VERTEX *tmpVertex; tmpVertex = new VERTEX[nIndex-1]; tmpVertex = vVertex; vVertex = new VERTEX[nIndex]; vVertex = tmpVertex; nVertexCount = nIndex+1; for (int x=0;x<nIndex;x++) delete &tmpVertex[x]; } return; } // Löscht alle Vertex-Punkte bool DeleteAll(){ for (int nVertex=0; nVertex<nVertexCount;nVertex++) { delete &vVertex[nVertex]; } return true; } thx:
Advertisement
vVertex = new VERTEX[0]; // bad, 0-sized array

use std::vector.

Edited by - Fruny on January 30, 2002 4:21:19 AM
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Yeah, what you said.
tmpVertex = new VERTEX[nIndex-1];
tmpVertex = vVertex;

vVertex = new VERTEX[nIndex];
vVertex = tmpVertex;

dieser code tut garichts, ausser spiecher verschwenden.
den ersten beiden zeilen weißt du tmpVertex einen speicherblock zu, und löschst gleich darauf den einziegen verweis auf ihn, du wirst ihn also weder wieder freigen können noch auf ihn zugreifen können.(der speieher ist verloren)
das gleiche gilt für die anderen beiden zeilen.
"Art is a lie that lets us recognize the truth." - Pablo Picasso
Well, the solution is quite simple. Just create the new, larger array, copy the contents of the smaller array into the new one, delete the old one and use the new one as the current array. But that isn''t very efficent, since each add causes a allocation and a copy operation. But it has been said before, you could just use the STL''s vector class.
By the way, when allocating with new [] you just have to use a single delete []. You MUST NOT delete each element seperately.
Wie kann ich dann ein arry neu definieren?

Oder gibt es sowas ähnliches wie realloc?

Edited by - Ethan on January 30, 2002 7:40:27 AM
ein beispiel:
  int *aArray = new int[4];int *pTmp = aArray;aArray = new int[5];memcpy(aArray,pTmp,4*sizeof(int));delete []pTmp;  
"Art is a lie that lets us recognize the truth." - Pablo Picasso

This topic is closed to new replies.

Advertisement