devxlogo

How to Initialize an Array

How to Initialize an Array

Question:
How do you initialize or assign values to an array in a class?

Answer:
The short answer is that you can’t initialize an array member as you would initialize a scalar data member. You can use memset to zero all the elements of the array inside the constructor’s body or use a loop that assigns values to each array element.

class A{ private:  int ar[10]; public: A()  {   for (int i=0; i<10; ++i)   ar[i] = i; }}

In most cases, it's best to use a vector object instead of a built-in array, thereby avoiding the initialization problem right from the start:

class A{private:std::vector < int > vi;//instead of array//...};

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist