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]);
I understand that enclosing () at the end should initialize all elements to zero. However, I noticed the opposite. Here is the output to the console:
buffer[0:3] = [-120][-85][-45][0]
How to make the new initializer work correctly?
Note. I know that I can use std::fill , but I'm curious why the new initializer does not work as advertised .
edit: Here is my revised approach with std::fill , which gives the correct behavior. But I would still like to know why this is 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]);
It is output:
[0][0][0][0]
source share