Reputation: 805
I have an incoming unitialized string. I want to remove all the uninitialized memory characters after "Keep" (Keep췍췍췍췍췍췍). Here is my code:
#include <windows.h>
#include <conio.h>
int main()
{
WCHAR* sNew = new WCHAR[10];
sNew[0] = 'K';
sNew[1] = 'e';
sNew[2] = 'e';
sNew[3] = 'p';
_getch();
}
How do I achieve this? In this example, I know the length I want to keep is the first four elements of the array, BUT, I need to code it for varying lengths.
I read that the '췍' symbol is the default for Visual Studio in Debug mode, so in release mode it could be
Upvotes: 1
Views: 489
Reputation: 1
You can use std::fill
as shown below:
WCHAR* sNew = new WCHAR[10];
std::fill(sNew, sNew + 10, 'a'); //i have used `a` as an example you can chose some other character according to your needs/preference
Or if you want to set characters after Keep
in your example you could do:
WCHAR* sNew = new WCHAR[10];
sNew[0] = 'K';
sNew[1] = 'e';
sNew[2] = 'e';
sNew[3] = 'p';
std::fill(sNew + 4, sNew + 10, 'a'); //note the + 4 used here
Also do note that you can value initialize all the elements of the array as shown below:
WCHAR* sNew = new WCHAR[10](); //note the empty pair of parenthesis
Upvotes: 1
Reputation: 264749
You can initialize all members of the array like this:
#include <windows.h>
#include <conio.h>
int main()
{
WCHAR* sNew = new WCHAR[10]{0}; // Set all members to zero.
WCHAR aNew[10]{0}; // Set all members to zero.
}
Upvotes: 1
Reputation: 82026
You can zero out the entire memory with memset:
WCHAR* sNew = new WCHAR[10];
memset(sNew, 0, 10*sizeof(WCHAR));
If you're using this memory as a c-string, then you really just need to terminate the string with a null character.
WCHAR* sNew = new WCHAR[10];
sNew[0] = 'K';
sNew[1] = 'e';
sNew[2] = 'e';
sNew[3] = 'p';
sNew[4] = '\0';
Upvotes: 1
Reputation: 18930
Practically, I'd suggest a few things
string
type, letting the compiler optimize it (const for fixed strings)
std::string const foo = "bar";
Upvotes: 0