0

So I have an array of vertices and I am trying to fill in the array with data from a file.

Right now my code looks like the following:

    int VertexCount = Input.get();
    MVertex Vertices[4] =
    {
        {0.0f, 0.0f, 0.0f,},
        {1.0f, 0.0f, 1.0f,},
        {0.0f, 0.0f, 1.0f,},
        {1.0f, 0.0f, 0.0f,},
    };

Right now it works just fine, except for using VertexCount to initialize the size of the array, but I want to get it so depending on the vertex count I need a for-loop to fill in the data for me. I wanna keep the same array format because for some reason it doesn't work any other way, but like this. I was thinking something along the lines of:

    int VertexCount = Input.get();
    MVertex Vertices[VertexCount] =
    {
        for (int i = 0; i < VertexCount; i++)
        {
            {Input.get(), Input.get(), Input.get(),},
        }
    };

But that doesn't work I just get some syntax errors. Can someone please show me how to write it?

1
  • Please edit your question to include the declaration for MVertex. Commented Jul 26, 2013 at 18:45

2 Answers 2

2

You are trying to do too many things all at one time. You need to break this up into two steps:

  1. Declare the array and allocate the array:

    int VertexCount = Input.get();
    MVertex* Vertices = new MVertex[VertexCount];
    
  2. Initialize the elements of the array:

    for (int i = 0; i < VertexCount; i++)
    {
        MVertex v;
        v.x = Input.get();
        v.y = Input.get();
        v.z = Input.get();
    
        Vertices[i] = v;
    }
    

Note that I create the MVertex object separately. In my opinion, this makes the intent of your code more clear. It also helps you write the code because you concentrate on one thing at a time instead of trying to do several steps all at once with more complex syntax.

I also assume the three fields in MVertex are named x, y, and z; change these as appropriate.

Since this code allocates a dynamic array, you must free the allocated memory when you are finished using it with the statement

delete[] Vertices;
Sign up to request clarification or add additional context in comments.

Comments

-1

To create an array of variable size, use the new operator

MVertex* Vertices = new MVertex Vertices[VertexCount];

to create the array on the heap (and remember to delete[] it later), or use an STL container like std::vector.

1 Comment

This is only a partial answer since it does not illustrate how to initialize the elements of the allocated array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.