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?
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.
Syntax: Dim array_name() As Integer.
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.
char* c = new char[length]();
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]();
]
Maybe use std::fill_n()
?
char* c = new char[length];
std::fill_n(c,length,0);
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