small_potato
small_potato

Reputation: 3197

A dynamic 2 dimensional array in C++?

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.

Upvotes: 2

Views: 442

Answers (3)

mloskot
mloskot

Reputation: 38912

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

Upvotes: 1

kennytm
kennytm

Reputation: 523304

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.)

Upvotes: 1

JRL
JRL

Reputation: 77993

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

Upvotes: 5

Related Questions