What is the difference between:
int messageLen = 25; char* message = new char [messageLen + 1];
This allocates a char
array of 26, normally for 25 characters and a trailing \0
.
int messageLen = 25; char* message = new char (messageLen + 1);
Allocates a single char
and gives it the value 26.
delete(message);
delete [] message;
delete[]
frees memory allocated by new[]
, delete
(w/o []
) does the same for memory allocated by new
; for efficiency, C++ doesn't keep track of this itself.
I read some articles on this topic, but none of them give me the exact answer.
It sounds like you may need a good C++ book.
I am beginner in C++, I'd be very grateful for some example!
All of the above is now considered fairly advanced C++, "beginners" shouldn't concern themselves with it at all. There are very few reasons to use new
/delete
and/or new[]
/delete[]
; avoid them unless you really know what you're doing.
The easiest way to deal with string data is to use std::string
. If you really need an array, look to std::array
or std::vector
.
constexpr size_t messageLen = 25;
std::array<char, messageLen+1> message;
If you don't have std::string
or std::vector
, are you sure you're really writing C++ code? Probably not (C with classes?). Although std::array
was added in C++11, so some really old environments may not have that.
But even then, reasonable facsimiles of these components can be written which still avoids the use of new
, et. al. in normal client code.