Ying said:
Hi,
whats the difference between:
char* a = new char;
"a" is a pointer to a character, initialized by the expression new char.
The expression new char allocates memory for one character from the free
store and (according to the current wording of the standard) initialized it
by doing nothing. So "a" will point at that "random" character in the free
store (sometimes called heap).
If new char cannot allocate memory for one object of type char it will throw
an std::bad_alloc exception, which will be either caught by an appropriate
ctach-handler or will cause the system to call a function named terminate(),
which will by default call a function named abort() and that one will stop
the programs' execution.
"b" is a pointer to a character, initialized by the expression new char[10].
The expression new char[10] allocates a block of continuous memory for 10
character from the free store and (according to the current wording of the
standard) initialized it by doing nothing. After initialization "b" will
point at the first of those 10 "random" characters in the free store
(sometimes called heap).
Rest is the same as before.
This one can be many things. So let's skip initialization and meaning
(because it can be namespace scope or automatic or member declaration) and
let's just go for the type.
"c" is an array of 10 characters. This means that it has the type: array of
10 characters. When using "c" in certain expressions it will (so-called)
decay into a pointer to the first element of that array. In such a case it
will behave much like "b" before, except that the memory area belonging to
"c" is not necessarily from the free-store:
c[2]; // third element of c
b[2]; // third element of b
It is important to note that while many many times "c" will behave as a
pointer to the first element of the array it represents, it is not one. It
just can behave as one (in certain expressions) for our convenience.