Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to initialize an allocated array in C++?

How to write this in another (perhaps shorter) way? Is there a better way to initialize an allocated array in C++?

int main(void) {
   int* a;
   a = new int[10];
   for (int i=0; i < 10; ++i) a[i] = 0;
}
like image 591
Prasoon Saurav Avatar asked Jul 14 '10 13:07

Prasoon Saurav


People also ask

What is the best possible way to initialize an array?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

What is the correct way of initializing an array in c?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you initialize a dynamically allocated array?

It's easy to initialize a dynamic array to 0. Syntax: int *array{ new int[length]{} }; In the above syntax, the length denotes the number of elements to be added to the array.

How do you initialize an array in c with default values?

Initialize Arrays in C/C++int arr[] = { 1, 2, 3, 4, 5 }; The array elements will appear in the same order as elements specified in the initializer list. c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.


1 Answers

 int *a =new int[10](); // Value initialization

ISO C++ Section 8.5/5

To value-initialize an object of type T means:

— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;

— if T is an array type, then each element is value-initialized;

otherwise, the object is zero-initialized

For differences between the terms zero initialization, value initialization and default initialization, read this

like image 72
Prasoon Saurav Avatar answered Sep 30 '22 17:09

Prasoon Saurav