1

I'm trying to translate some C code to D, and I've come across this:

char[] welcome = "\t\tWelcome to the strange land of protected mode!\r\n";

It gives this warning:

main.d:5:18: error: cannot implicitly convert expression ("\x09\x09Welcome to the strange land of protected mode!\x0d\x0a") of type string to char[]
    5 | char[] welcome = "\t\tWelcome to the strange land of protected mode!\r\n";
      |                  ^

How do I do this without typing each character out individually in the array?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76

2 Answers2

4

As already mentioned, strings already are an array of chars. In fact, here is the definition of string:

alias string = immutable(char)[];

(from object.d)

A string thus differs from a char[] only in that the contents of the array is immutable.

  • Depending on your goal, you may not need a char[] after all, and string will work as well.
  • If you need the array to be writable (i.e. you expect welcome[2] = 'x'; to work), then using .dup will create a copy at runtime.
  • Sometimes C function declarations are not properly annotated with const, and will not accept pointers to immutable characters. In this case, using a cast is acceptable.
  • I don't think there is a language feature to place a string literal directly in a writable data segment, in the same way that static char[] s = ['a', 'b', 'c']; does, but it's likely doable as a template or CTFE function.
Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114
3

12.16.1 - Strings

  1. A string is an array of characters. String literals are just an easy way to write character arrays. String literals are immutable (read only).

    char[] str1 = "abc";                // error, "abc" is not mutable
    char[] str2 = "abc".dup;            // ok, make mutable copy
    immutable(char)[] str3 = "abc";     // ok
    immutable(char)[] str4 = str1;      // error, str4 is not mutable
    immutable(char)[] str5 = str1.idup; // ok, make immutable copy
    
  2. The name string is aliased to immutable(char)[], so the above declarations could be equivalently written as:

    char[] str1 = "abc";     // error, "abc" is not mutable
    char[] str2 = "abc".dup; // ok, make mutable copy
    string str3 = "abc";     // ok
    string str4 = str1;      // error, str4 is not mutable
    string str5 = str1.idup; // ok, make immutable copy
    

So:

char[] welcome = "\t\tWelcome to the strange land of protected mode!\r\n".dup;
Swordfish
  • 12,971
  • 3
  • 21
  • 43