Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Dealing with strings copy

Part of ArraysCategory

Description

This example shows several ways to declare strings and how their copy is managed.

Example

import std.c.stdio;
import std.string;

int main(char[][] args)
{
    char[] s = new char[4];
    char[] s1;
    char[] s2;
    char[4] s3;
    char[] s4 = "hello";
    char[6] s5 = "hello1"; 
    
    s = "a";
    printf("s = %.*s\n", s);
    // memory is automatically allocated
    s1 = "b";
    printf("s1 = %.*s\n", s1);
    // in this way a reference is copied ...
    s2 = s4;
    printf("s2 = %.*s\n", s2);
    s4[3] = 'p';
    s4[4] = '\0';
    // ... and the string s2 IS modified too
    printf("s2 = %.*s\n", s2);
    // s3 = "c"; no: static strings cannot change references
    // but we can copy in them new values without worrying about dup (here we copy the first chars)
    // we must use slices to match the dimensions
    s3[] = s5[0..4];
    s = s5;
    s1 = s5.dup;
    s5[3] = 'p';
    s5[4] = '\0';
    // static arrays will always have a copy of data
    printf("s3 = %.*s\n", s3);
    // in this case the reference IS changed
    printf("s = %.*s\n", s);
    // to avoid the previous behaviour we must duplicate the contents with dup
    printf("s1 = %.*s\n", s1);
    return 0;
}

Comments

This example will produce a segmentation fault on Linux because string literals are read-only.

Source

Link http://www.dsource.org/tutorials/index.php?show_example=150
Posted by Anonymous