I am trying to allocate memory for a string of variable length n
. Here is my attempt:
int n = 4; // Realistically, this number varies.
char* buffer = new char[n * 512]();
printf("buffer[0:3] = [%d][%d][%d][%d]\n", buffer[0], buffer[1], buffer[2], buffer[3]);
My understanding is that the inclusion of ()
at the end should initialize all elements to zero. However, I noticed otherwise. Here is the output to the console:
buffer[0:3] = [-120][-85][-45][0]
How do I make the new
initializer work properly?
Note: I am aware that I can use std::fill
, but I'm curious as to why the new
initializer doesn't work as advertised.
edit: Here is my revised approach with std::fill
, which gives the correct behavior. But I'd still like to know why it's necessary.
int n = 4; // Realistically, this number varies.
char* buffer = new char[n * 512]();
std::fill(&buffer[0], &buffer[n * 512], 0)
printf("buffer[0:3] = [%d][%d][%d][%d]\n", buffer[0], buffer[1], buffer[2], buffer[3]);
This outputs:
[0][0][0][0]