Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to statically-initialize a dynamically-allocated array in C++?

In C++, I can statically initialize an array, e.g.:

int a[] = { 1, 2, 3 };

Is there an easy way to initialize a dynamically-allocated array to a set of immediate values?

int *p = new int[3];
p = { 1, 2, 3 }; // syntax error

...or do I absolutely have to copy these values manually?

like image 202
neuviemeporte Avatar asked Sep 21 '10 14:09

neuviemeporte


People also ask

How do you initialize a dynamic allocated array?

Initializing dynamically allocated arrays. It's easy to initialize a dynamic array to 0. Syntax: int *array{ new int[length]{} };

Does C allow dynamic allocation of arrays?

We can create an array of pointers of size r. Note that from C99, C language allows variable sized arrays. After creating an array of pointers, we can dynamically allocate memory for every row.

Is array static or dynamic in C?

Static array means the size of an array is static and dynamic array means the size of an array is dynamic. Once the array is created its size cannot be modified.

What is the difference between a statically allocated array and a dynamically allocated array in C?

Static Memory Allocation is done before program execution. Dynamic Memory Allocation is done during program execution. In static memory allocation, once the memory is allocated, the memory size can not change. In dynamic memory allocation, when memory is allocated the memory size can be changed.


2 Answers

You can in C++0x:

int* p = new int[3] { 1, 2, 3 };
...
delete[] p;

But I like vectors better:

std::vector<int> v { 1, 2, 3 };

If you don't have a C++0x compiler, boost can help you:

#include <boost/assign/list_of.hpp>
using boost::assign::list_of;

vector<int> v = list_of(1)(2)(3);
like image 117
fredoverflow Avatar answered Sep 20 '22 01:09

fredoverflow


You have to assign each element of the dynamic array explicitly (e.g. in a for or while loop)

However the syntax int *p = new int [3](); does initialize all elements to 0 (value initialization $8.5/5)

like image 39
Chubsdad Avatar answered Sep 18 '22 01:09

Chubsdad