简体   繁体   中英

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.

您需要使用指针,或者在不知道大小的情况下使用动态调整大小的容器,例如std::vector

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM