开发者

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 fi开发者_如何学编程le:

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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜