Why isn't my dynamic array method doesn't work for this type?
vit
vit at vit.vit
Thu May 5 12:42:28 UTC 2022
On Thursday, 5 May 2022 at 11:49:29 UTC, vit wrote:
> On Thursday, 5 May 2022 at 10:40:44 UTC, rempas wrote:
>> I have created a structure that is a actually an array that
>> allocates memory and growths. It is a template and it has
>> worked with a couple of types that I have tried with. It
>> doesn't work with one tho and I cannot understand why. I will
>> list the smallest possible code I could. Keep in mind that it
>> is a couple of code. For anyone that wants to read it, keep in
>> mind that I have to make this code work with LDC and using
>> "-betterC".
>>
>> [...]
>
> ```d
> this.capacity += DEF_VEC_REALLOC_SIZE;
> //realloc(this.ptr, T.sizeof * DEF_VEC_REALLOC_SIZE);
> this.ptr = realloc(this.ptr, T.sizeof * this.capacity);
> //<<--
> ```
```d
void add(T element) {
if (this.capacity == this.length) {
this.capacity += DEF_VEC_REALLOC_SIZE;
this.ptr = realloc(this.ptr, T.sizeof * this.capacity);
if (!this.ptr) { // Re-allocation error check
fprintf(stderr, "Error: Could not allocate more memory for
the *%s object! Exiting...",
cast(char*)(T).stringof);
exit_prog(1);
}
}
this.ptr[this.length++] = element;
}
```
More information about the Digitalmars-d-learn
mailing list