tags:

views:

98

answers:

3

I am trying to build a 2 dimensional array in C++ while I don't know how many rows I will have. Here is some code:

In the header file:

class model
{
         ... ...

    float vertices[][3];

         ... ...
}

And in the .cpp file:

 istringstream iss(str);
 for (int i = 0; i <=2; i++)
     {
         iss >> vertices[counter][i];
     }

Is this a proper way to handle it? I got a segmentation fault, I just want to make sure it's not caused by the way I use arrays. Also is there a better way to handle this, thanks.

+5  A: 

You need to either use pointers, or use a dynamically resizable container such as std::vector when you don't know the size.

JRL
And I'd recommend wrapping a *single* vector. Use math to calculate it's 1D index from a 2D index. Usually simpler and faster.
GMan
@GMan: I would not say so as one of the dimension is fixed (3).
KennyTM
@GMan: But if the application requires operations like "insert into row 1 when there are things in row 2," then shifting everything around can become prohibitively expensive. Actually, if the nested vectors are staggered at all it will become expensive...
Travis Gockel
`std::vector< std::tr1::array<float, 3> >`
mloskot
Missed that one was fixed. @mloskot's solution seems nice.
GMan
+1  A: 

A Type variable[]; appears in a struct/class definition actually means a zero-length array which is a gcc extension (ISO C++ doesn't allow this) for a flexible array with a variable length known in compile-time.

(You should use std::vector or new Type[n] as others have suggested.)

KennyTM
+1  A: 

In case one of dimensions is of static size, here is one of many possible solutions:

typedef float triplet[3];
std::size_t const n = 10;
triplet* a = new triplet[n];

for (std::size_t i = 0; i < n; ++i)
{
    // ...
}
delete [] a;

I'd suggest to use Boost.MultiArray.

A very similar question has been already asked and answered with plenty of examples

C++ dynamically allocated array of statically dimensioned arrays

mloskot