C-style arrays can be used as data members, both as fixed-size arrays or as dynamic arrays. The following examples demonstrate how they could be used as one-dimensional data members.
class a {
private:
int b[10] {0}; // in-class initialisation (all elements zero).
public:
int& operator[] (unsigned index) {
if (index>=10) throw std::range_error();
return b[index]; }
};
class c {
public:
c (unsigned sz=10): size(sz), p (size?new int[size]:nullptr) {
memset (p, 0, size); }
c (const s& _s): size(_s.size), p (size?new int[size]:nullptr) {
if (size) memcpy (p, _s.p, size); }
c (s&& _s): size(_s.size), p (_s.p) { _s.p=nullptr; } // swap resources
c& operator= (const s& _s) {
if (p) delete [] p;
size = _s.size;
p = (size?new int[size]:nullptr);
if (size) memcpy (p, _s.p, size); }
c& operator= (s&& _s) {
size = _s.size;
p = _s.p;
_s.p=nullptr; } // swap resources
~c() { if (p) delete [] p; }
int& operator[] (unsigned index) {
if (index>=size) throw std::range_error();
return p[index]; }
private:
unsigned size {0};
int* p {nullptr};
};
A much simpler approach would be to use std::array<int> and std::vector<int> instead of primitive C-style arrays.
Chat with our AI personalities
Yes you can store non primitive data type variables in an array. String is a non primitive data type. You can declare a string array as: String a[]=new String[10];
An array is a primitive data type. It is the element type that may or may not be primitive.
No, it can be array, structure or union as well.
Depends on the context of the question you were asking from, there are 2 distinct answers: Yes and NO. In the narrowest definition, any array is NOT a primitive data type in C#. Hence a string array is NOT a primitive data type in that context. A string itself, however, is a primitive data type. Some developers would like to extend the definition of "primitives" into the arrays, collections, and Enumeration. Thus, in this context, an array of string IS a primitive data type.
Only if the non-primitive data types are actually controls, such as an array of label controls, or an array of edit boxes. However, a control array is still an array. The only difference is that the values will likely be resource handles (objects that refer or point to the actual object which will be stored elsewhere in memory) rather than an actual value itself. That is, an array of primitive data types stores the actual value in the array itself.