What's the difference between new char[10] and new char(10)
The first allocates an array of 10 char's. The second allocates one char initialized to 10.
Or:
The first should be replaced with std::vector<char>
, the second should be placed into a smart pointer.
new char[10];
dynamically allocates a char[10] (array of char, length 10), with indeterminate values, while
new char(10);
again, dynamically allocates a single char, with an integer value of 10.
char *a = new char[10];
...
delete [] a;
The above dynamically allocates and deallocates 10 contiguous memory slots that can be used to store chars.
char *a = new char(10);
...
delete a;
The above dynamically allocates and deallocates one memory slot that is initialized with the integer value 10
, equivalent to the char value '\n'
.
Do NOT use the std::vector<T>
if you do not first understand pointers. Knowing how memory allocation and pointers work will make you a better programmer.