Last update August 29, 2012

Doc Comments /
Arrays



Difference (last change) (no other diffs, normal page display)

Added: 10a11,15
== Pointers ==

Add to the sentence "These are simple pointers to data, analogous to C pointers." the following:

"albeit with the distinction that D pointers are dereferenced implicitly when used with a member access operator. E.g. ptr.fun() is same as (*ptr).fun()"


Arrays    

Table of contents of this page
Arrays   
Comments   
Pointers   
String Mutamumble Flavors   
Word Count example   
Special array type example   
Allocating dynamic arrays with new   
Example Error in Arrays: Usage   
Rectangular Arrays   
Slice Boundaries   
Array Operations   
Adding properties to arrays   
More explanation of dynamic array value/reference semantics   
Names "static" and "dynamic" confusing   
Array Initialization Template Tip   
C vs D Array Declaration Tip   
Associative Arrays   
Arrays as Keys   
Associative Array Basics   
Clearing an Associative Array   
Complexity of Associative Array Operations   
Links   

Comments    

Add your comments in a new or existing section below.

Pointers    

Add to the sentence "These are simple pointers to data, analogous to C pointers." the following:
"albeit with the distinction that D pointers are dereferenced implicitly when used with a member access operator. E.g. ptr.fun() is same as (*ptr).fun()"

String Mutamumble Flavors    

It would be nice if there was a prescriptive web page white paper which specified the when / where / why between:

  • char[]
  • const(char)[]
  • immutable(char)[]
    • invariant(char)[]
    • string
Also the recommended way to go from one to another.

String to char array:

   string s = "hello";
   char[] a = s.dup;

Char array to string:

   char[] a = "hello".dup;
   immutable(char)[] s = a.idup;

Here is one good prescriptive page: http://www.digitalmars.com/d/2.0/const3.html

Word Count example    

The word count example in http://www.digitalmars.com/d/2.0/arrays.html does not compile with dmd 2.026 (alpha).

Special array type example    

str is not read only, str1 is.

char[] str; char[] str1 = "abc"; str[0] = 'b'; // error, "abc" is read only, may crash

Allocating dynamic arrays with new    

The "Arrays" section does not mention how to dynamically allocate an array like int[][][]. This information can be found in the "Expression" section of the documentation: NewExpression

The easiest way to do it is:

    auto x = new int[][][](10,20,30);

Example Error in Arrays: Usage    

In the section 'Usage' in the 'Arrays' page: ( http://www.digitalmars.com/d/arrays.html), one of the examples shows:

    s = ...;	// error, since s is a compiled in static

I believe this is a typo and thus, it's supposed to be:
    s = t;      // error, since s & t are compiled static
                // and their references cannot be changed.

't' is declared at the top of the example as a static array, but is never used in the example as it should be.

- JoseSantos -

Rectangular Arrays    

Remove the sentence ...
In other languages, this would be called a multidimensional array and be declared as: 
double matrix[3,3];
as it can be misread as a D example and doesn't really help highlight D syntax.

Slice Boundaries    

The declaration of boundaries for slices gives the first index, and then the index just past the actual last element of the slice. There were several choices for the syntax, but this choice was picked as most consistent with how arrays are declared. After all, "int[3] myArray" creates an array with indices 0 through 2.

Array Operations    

The arrays section doesn't mention what == does with arrays. It would be nice to include the identity

 x[i .. j] ~ x[j .. k] == x[i .. k]
with a brief explanation to illustrate how slicing, concatenation and equality work with arrays.

Adding properties to arrays    

It should be added that free functions that accept as parameter an array can be used as properties for all arrays of the same type as the array accepted by the functions. This is one of the clever features I like more in D.

char [] something(char [] x ) { return x ~ " manipulated"; }
char [] input;
input.something();

Personally I think this hack confuses properties with user code and since the .sort and .reverse properties change the array inplace and user code should be COW it can be confusing to make user code look like properties. -- BenHinkle

More explanation of dynamic array value/reference semantics    

It's easy to confuse what has value and reference semantics with dynamic arrays. The usage of dynamic arrays says "Dynamic arrays consist of a length and a pointer to the array data. Multiple dynamic arrays can share all or parts of the array data." It should be spelled out that the length and pointer are copied by value and passed to functions by value. Possibly also have a whole section with examples showing how changing the length of one array doesn't change the length of another --BenHinkle

Names "static" and "dynamic" confusing    

A few threas on the main newsgroup suggested renaming "static" arrays since the word static it very overloaded. Some suggestions:

  • resizable/nonresizable array

Array Initialization Template Tip    

The current implementation of D arrays does not allow the inline initalizer syntax for non-static arrays. This means that code like char[][] foo = ["one","two","three"]; will result in a compiler error.

Try using the following template as a work-around:

template makeArray(T){
  T[] makeArray(T[] newArray...){
  	return newArray.dup;
  }
}

Then you may use the following syntax as a stand-in for an inline initalizer:

char[][] foo = makeArray!(char[])("one","two","three");

(by EricAnderton)

The reason why direct intialisation above is refused is that D does not perform auto-conversion from immutable (string) to mutable (char[]) arrays. What makeArray does using ".dup". But the following are ok:

char[][] foo = ["one".dup, "two".dup, "three".dup];
immutable(char)[][] bar = ["one", "two", "three"];
string[] baz = ["one", "two", "three"];

DenisDerman

C vs D Array Declaration Tip    

When migrating from C to D syntax you should be aware that the C array declaration

int arr[2][3][4];

is in native D syntax written as

int[4][3][2] arr;

with reversed order of the indices.

(by MichaelButscher?)

Associative Arrays    

Arrays as Keys    

The user should know that he needs to duplicate keys before using them to create new associative array entries. [BenHinkle: not always duplicate - they just shouldn't change a key in an array]

Source: NG:digitalmars.D/12062

Associative Array Basics    

  • Existence of a key can be tested using the 'in' operator. Example:
     if ("foo" in AA) { return AA["foo"]; } 
  • Indexing an associative array as an rvalue throws an ArrayBoundsError? exception if the key is not present. Example:
     writefln(AA["bad_key"]);
  • Indexing an associative array as an lvalue creates a new entry if the key was not present before, or overwrites the previous value if the key was present. Example:
     AA["new_key"] = 5; 
  • Calling remove on a non-existent element does NOT throw an exception. Example:
     AA.remove["bad key"]; // nothing happens 

Clearing an Associative Array    

The D associative array is a reference type. A null associative array reference will automatically initialize itself on the first insertion. Reassigning an associative array reference to null will make the reference refer to an empty array.

Example:

int[int] a = [1:2,3:4];
int[int] b = a;
assert(b.length == 2);
a = null;
assert(a.length == 0);
assert(b.length == 2);

There is no standardized way to clear the actual array referred to by the reference. One implementation that works with the current D ABI:

private struct BB { void*[]b; size_t nodes; }

private union ToPtr(T) {T x; void * ptr; }

void clear(T,E)(T[E] aa) {
    ToPtr!(typeof(aa)) toptr;
    toptr.x = aa;
    BB* b = cast(BB*) toptr.ptr;
    if (b) {
        b.b = null;
        b.nodes = 0;
    }
}

Example:

int[int] a = [1:2,3:4];
int[int] b = a;
assert(b.length == 2);
a.clear();
assert(a.length == 0);
assert(b.length == 0);

Complexity of Associative Array Operations    

Q: What is the complexity for associative array operations?

A: AA's are implemented as a chaining hash table with binary trees replacing the slists (thus the need for opCmp instead of opEquals for stored objects). So AA operations should be O(1).

Links    


FrontPage | News | TestPage | MessageBoard | Search | Contributors | Folders | Index | Help | Preferences | Edit

Edit text of this page (date of last change: August 29, 2012 8:20 (diff))