Arrays of Structs

Started by
6 comments, last by Zahlman 18 years, 2 months ago
Hi, I'm having a problem creating an array of structs. How would i create one 'on the fly'?

struct Vertex
{
	float x,  
		  y,
		  z,
		  u,
		  v;
};

int VerticeNum;  //Number of vertices

Is the vertex. There are an unknown number of vertices in the model. so i read in the variable for the number of vertices then try to create an array of them based on that variable, but i dont konw how to do this.
Advertisement
Since no programming language is given, I'll assume C#. You declare an array variable as:

Vertex [] my_vertex_array;

You can dynamically create an array by using

Vertex [] my_vertex_array = new Vertex[VerticeNum];
I guess you mean this?

Vertex* p = new Vertex[VerticeNum];


/Edit: Beaten. Unless you meant C++ after all. :)
Use a Vector?

vector<Vertex> v(VerticeNum);

Not sure if thats correct, bit of a noob to the specifics of C++ myself.
www.aidanwalsh(.net)(.info)
meant c++. Thanks a lot for the help everyone. :)
Quote:Original post by Winegums
How do i return the values of these to something outside the function?


Without seeing the context of the problem you're describing, you could pass the array into the function by reference and update the values in the function. Or if you want to get the values out of a single struct, you could return a new vertex object with the values.

There's lots of ways to do it depending on the situation. I can't really say which is a good way for you without seeing what you're trying to do.

EDIT* That's weird, where did this question go that I responded to? It was here when I started. Oh well. Best of luck.
int swap_and_add( int *a, int *b ){  int c = *b;  *b = *a;  *a = c;  return *a + *b;}int a = 5;int b = 17;printf("%d %d\n",a,b);int c = swap_and_add(a,b);printf("%d %d %d\n",a,b,c);


Generates:
5 1717 5 22

We''re sorry, but you don''t have the clearance to read this post. Please exit your browser at this time. (Code 23)
In C++, this is spelled:

int swap_and_add(int & a, int & b) {  std::swap(a, b);  return a + b;}int a = 5;int b = 17;std::cout << a << ' ' << b << std::endl;int c = swap_and_add(a,b);std::cout << a << ' ' << b << ' ' << c << std::endl;


(Edit: You also forgot to take addresses when calling the function in the C version. You should have 'swap_and_add(&a, &b)' :) )

This topic is closed to new replies.

Advertisement