Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you initialise a dynamic array in C++?

Tags:

c++

arrays

How do I achieve the dynamic equivalent of this static array initialisation:

char c[2] = {};  // Sets all members to '\0';

In other words, create a dynamic array with all values initialised to the termination character:

char* c = new char[length]; // how do i amend this? 
like image 200
tgh Avatar asked Jan 08 '10 18:01

tgh


People also ask

How do you initialise in array in C?

An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.

What is the syntax of dynamic array?

Syntax: Dim array_name() As Integer.

Can we create a dynamic array?

In C++, a dynamic array can be created using new keyword and can be deleted it by using delete keyword. Let us consider a simple example of it.


3 Answers

char* c = new char[length](); 
like image 105
Fred Avatar answered Oct 02 '22 13:10

Fred


Two ways:

char *c = new char[length]; std::fill(c, c + length, INITIAL_VALUE); // just this once, since it's char, you could use memset 

Or:

std::vector<char> c(length, INITIAL_VALUE); 

In my second way, the default second parameter is 0 already, so in your case it's unnecessary:

std::vector<char> c(length); 

[Edit: go vote for Fred's answer, char* c = new char[length]();]

like image 25
Steve Jessop Avatar answered Oct 02 '22 12:10

Steve Jessop


Maybe use std::fill_n()?

char* c = new char[length];
std::fill_n(c,length,0);
like image 20
mrkj Avatar answered Oct 02 '22 12:10

mrkj