Variable Length Arrays in C++

Soldato
Joined
18 Feb 2003
Posts
5,817
Location
Chester
Hi, just wondering how i could control the length of an array using a variable.

e.g. i have the array -
Code:
		glBegin(GL_LINE_LOOP);
		glVertex2iv(poly[0]);
		glVertex2iv(poly[1]);
		glVertex2iv(poly[2]);
		glVertex2iv(poly[3]);
		glVertex2iv(poly[4]);
		glEnd();

obviously taking 5 points...but if i wanted the length to be as long as a variable (points) then how could this be done?
 
Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
Im using sumthing similar for my OpenGL work.

1. Basically create a new temp array of the size u want.
2. Copy old values in
3. Delete contents of old array
4. Point old array to new array.


so in your case you need sumthing like this:

Code:
void increaseArray(int numberOfNewPoints)
{

  Poly *temp = new Poly[numberOfPoints + numberOfNewPoints];

  // Copy new values into array
  for (int i=0; i < numberOfPoints; i++)
  {
    temp[i].x            = this->poly[i].x;
    temp[i].y            = this->poly[i].y;
  }

  // Free old array memory
  delete [] poly;
  
  // Now points to new array
  this->poly = temp;
  
  // Increase number of points
  this->numberOfPoints += numberOfNewPoints;

}

numberOfPoints is just a global variable holding how many points you have.

You can use C vectors which do all this for you.
 
Last edited:
Soldato
OP
Joined
18 Feb 2003
Posts
5,817
Location
Chester
cheers Jon, i've used something a little easier in myDisplay -
Code:
	for(int p( 0 ) ; p < points ; ++p)
		glVertex2iv(poly[p]);


but now i can't figure out how you get the maths behind it to relate to the code to draw out a polygon....the code being -
Code:
void myDisplay()
{
	const PI = 3.141592;
	int points, radius;
		
	glClear(GL_COLOR_BUFFER_BIT);		//Clear Screen
	glBegin(GL_POINTS);
	glPushMatrix();
	glTranslatef(x,y,0);
	//glRotate(angle, 0,0,1);
	radius = 2*PI/points;
	for(int p( 0 ) ; p < points ; ++p)
		glVertex2iv(poly[p]);

	for( int a(0);a<points;++a)
	{
		float pointAngle = angle*a ;
		glVertex2f(cos(pointAngle),sin(pointAngle));	
	}
	angle = (360.0f/points) * (PI/180);	//Converts degrees to radians
	glPopMatrix();
	glutSwapBuffers();											

	glFlush();												
}

oh, and any idea why glRotate wont work (when not commented) but glTranslate does. I've got the idle code to make it move and the push and pop matrix so can't figure it out myself.... :confused:
 
Last edited:
Permabanned
Joined
13 Jan 2005
Posts
10,708
Use a std::vector. This behaves just like a c style array, but handles all memory allocation/deallocation and will grow/shrink as necessary.
 
Back
Top Bottom