Simon Adler said:
Hello,
in the last time I see a lot like:
float * foo = new float[42];
First question: This isn't right, isn't it?
Yes it's correct. It creates a type 'foo*'
('pointer to float') object, allocates an array of
42 type 'float' objects, and returns the address
of the first one ( foo[0] ), and stores that address
value in the pointer object 'foo'. Note however,
that none of the 42 type 'float' objects is
initialized, so they must be assigned valid
values in order to be able to access them
without undefined behavior.
It has to be:
float ** foo = new float[42]; ?????
No. Why do you feel it does?
Second Question
What is the difference to
float foo[42]; ??
The first form above dynamically allocates an array (which
means that the array 'lives' until you specifically deallocate
it with 'delete[]', or the program terminates). The form:
float foo[42];
defines either a 'static' (if this definition appears
at file scope) or 'automatic' (if this definition appears
at block scope) array of 42 type 'float' objects. In
the 'static' case, the array's lifetime is the duration
of program execution. Also, all 42 objects are zero-
intialized. In the 'automatic' case, the array's
lifetime is from its point of definition, up to the point
where the scope it's defined is exited. None of the
42 objects are intitialized, so evaluating any of them
results in undefined behavior. So in the 'automatic'
case, I recomment the form:
float foo[42] = {0}; /* Initializes all array members to zero */
(or specificy a list of initializers with values that make sense
for your application).
This will prevent inadvert evaluation of uninitialized
objects, and the resultant undefined behavior.
BTW I recommend not using 'new' and 'raw' pointers as
above without a compelling reason to do so. For 'collections'
of same-type objects, I recommend using a standard container
(e.g. vector) instead. The standard containers do all
their own memory management for you automatically. This
will reduce the possibility of memory leaks, corrupted
pointers, etc.
Which C++ book(s) are you reading?
-Mike