C++ Assigning heap memory to each element(struct) in array of structs -
i confused allocating memory struct.
consider this.
struct { .... } a* array = new a[5]; // here trying assign memory array[0] &(array[0]) = new a; << error
but give me error
lvalue required left operand of assignment`
i not sure on how assign memory struct a
array[0]
.
thank in advance.
a type a*
doesn't hold pointers should allocated individually new
. a*
contiguous block of memory holds 1 or more complete instances of a.
this means that
a* array = new a[3];
will allocate like
| | | |
and each "cell" large sizeof(a)
bytes. in case have 5 a
instances, constructed.
if want have indipendent instances allocated on heap don't need a*
a**
.
a** array = new a*[3];
this creates contiguous array of 3 a*
elements, pointers a
sort of:
| a* | a* | a* |
ad each cell large sizeof(a*)
.
now can assign element of array specific instance of allocated on heap. eg:
array[0] = new a();
which yields like
| a* | ... | | --> | |
Comments
Post a Comment