Reputation: 211
I do not plan on changing the size of my dynamic array. The reason I want to create a dynamic array of static arrays (which contain shorts) is so that I can return that array in a function (not defining the size of that array until I'm in that function).
My first question then, is how do I return such an array? Functions don't let you return a pointer without a type & I'm unable to find out how to define a pointer with type array
.
This brings me to my second question, which is how do I correctly define a dynamic array of static arrays? I have searched for this online, but none of the answers have been too helpful.
One way to do it is to declare: short (*array)[size]
but the problem with this is that I don't know how to initialize the array in that case, and size
has to be a literal.
I could do this:
typedef short column[size];
column * row = NULL;
row = malloc(rowMax * sizeof(column));
row[0][0] = 10;
but again, size
has to be a literal; and even if size
is a literal, I receive an error stating that a value of type "void *" cannot be assigned to an entity of type "column *".
If any of you have a solution that doesn't use vectors that would be greatly appreciated; as the vector class is larger than the array class.
Upvotes: 1
Views: 324
Reputation: 81
For the sake of saving time, just create a vector of static arrays
std::vector<std::array<Type, n>>
Not sure why the size difference matters, it's only a few Kb.
Also, if you're going to write C code in a C++ app... you're gunna have a bad time.
Upvotes: 1
Reputation: 17940
In C++11 one could use std::array
from <array>
and do:
constexpr std::size_t const cols = 42u; // static size
using MyStaticArray = std::array<short, cols>; // static array type
// Or in C++03 and earlier: typedef short MyStaticArray[42u];
std::size_t const rows = someValue; // dynamic size
MyStaticArray * dynamicArray = new MyStaticArray[rows];
// Or better: std::vector<MyStaticArray> dynamicArray(rows);
for (std::size_t row = 0u; row < rows; ++row)
for (std::size_t col = 0u; col < cols; ++col)
dynamicArray[row][col] = rows * cols;
PS: Also give upvotes to Remy Lebeau below for his comments helped to improve this post.
Upvotes: 2