Sign in to follow this  

Arrays of Structs

This topic is 4341 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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];

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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 17
17 5 22

Share this post


Link to post
Share on other sites
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)' :) )

Share this post


Link to post
Share on other sites

This topic is 4341 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this