Home >Backend Development >C++ >How Can I Statically Declare a 2-D Array as a C Class Data Member?
Statically Declaring a 2-D Array as a Class Data Member
In C , a class can contain a 2-D array as a data member. However, dynamic memory allocation is typically used to create these arrays. To avoid this and achieve contiguous memory allocation, one can consider declaring the array statically.
A statically declared 2-D array within a class can be initialized using a custom constructor. Here's an example:
class Grid { public: unsigned NR, NC; double Coordinates[NR][NC]; Grid(unsigned rows, unsigned columns) : NR(rows), NC(columns) {} };
This class defines a 2-D array Coordinates with dimensions NR and NC. The constructor initializes NR and NC when the object is created.
While it is possible to declare a 2-D array statically in C , it is important to note that the size of the array must be known at compile time. This can be a limitation in some scenarios.
An alternative approach is to use a vector of vectors (std::vector
The above is the detailed content of How Can I Statically Declare a 2-D Array as a C Class Data Member?. For more information, please follow other related articles on the PHP Chinese website!