On 11/20/2012 06:25 AM, Namespace wrote:
Is there any need for 'smart' or 'compressed' arrays?
In my last projects I had some situations where I need an array, but
only for one scope. But I could not use static arrays, because I didn't
know the size at compile time. So I used 'alloca'. But 'alloca' has a
terrible interface and in some few cases I had to append x elements. So
I used a dynamic array. But dynamic arrays live longer as the lifetime
of the scope. Furthermore dynamic arrays costs more memory as I needed,
because the capacity of them is n * 2 + 1, but in my cases I need only n.
So what I need was an array, which lives only for one scope (freed
memory after leaving scope) and which hasn't more elements/capacity as I
need.
Am I wrong and dynamic arrays are the solution? Or is there need for
such 'compressed' arrays?
Another solution would be to improve the interface of alloca, but it
would be still not resizable.
The following program makes a slice from GC-allocated memory (or a
fixed-size array as in the comment). The important part is 'buffer[0..10]'.
import std.stdio;
import core.memory;
void bar(int[] a) // Also try: int[10] a
{
writeln("param : ", a.ptr);
}
void foo()
{
int *buffer = cast(int*)GC.calloc(int.sizeof * 10);
scope (exit) GC.free(buffer);
writeln("buffer: ", buffer);
int[] a = buffer[0..10]; // Also try: int[10] a =
writeln("a : ", a.ptr);
foreach (i; a) {
i = 42 + i;
}
bar(a);
}
void main()
{
foo();
}
Ali