Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the point of having static arrays

Tags:

d

static-array

I don't have a background in C or C++, so static arrays puzzle me a little. What are they for? Why are they allocated on the stack?

I imagine there's a performance benefit. Stack allocation is faster and there's no need for garbage collection. But why does the length need to be known at compile time? Couldn't you create a fixed-size array at runtime and allocate it on the stack?

Dynamic arays or slices in D are represented by a struct that contains a pointer and a length property. Is the same true for static arrays? How are they represented?

If you pass them to a function, they are copied in their entirety (unless you use ref), what is the rationale behind that?

I realize that dynamic arrays and slices are much more imprtant in D than static arrays, that's why the documentation doesn't dwell on them very long, but I'd still like to have a bit more background. I guess the peculiarities of static arrays have to do with how stack allocation works.

like image 766
fwend Avatar asked Dec 21 '22 02:12

fwend


1 Answers

static arrays hail from the C language where calls to (the slow) alloc were discouraged to the extreme because of memory leaks (when you forgot to free the allocated array), double freeing (as a result of...), dangling pointers (all dangers of manual memory management that can be avoided with GC)

this meant that constructs such as

int foo(char* inp){
    char[80] buff;
    strcpy(inp,buff);//don't do this this is a invite for a buffer overflow
    //...
    return 1;
} 

were common instead of the alloc/free calls where you need to be sure everything you allocated was freed exactly once over the course of the program

technically you CAN dynamically allocate on the stack (using assembly if you want to) however this can cause some issues with the code as the length will only be known at runtime and lessen possible optimization that the compiler may apply (unrolling an iteration over it for example)

static arrays are mostly used for buffers because of the fast allocation possible on the stack

ubyte[1024] buff=void;//assigning void avoids the initializer for each element cause we are writing to it first thing anyway
ubyte[] b;
while((b=f.rawRead(buff[])).length>0){
     //...
}

they can implicitly convert to a slice of the array (or explicitly with the slice operator []) so you can use them near interchangeably with normal dynamic arrays

like image 194
ratchet freak Avatar answered Jan 04 '23 10:01

ratchet freak