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;
}
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With