Search code examples
pointersd

Will an array of pointers be equal to an array of chars?


I have got this code:

import std.stdio;
import std.string;

void main()
{
    char [] str = "aaa".dup;
    char [] *str_ptr;
    writeln(str_ptr);
    str_ptr = &str;
    *(str_ptr[0].ptr) = 'f';
    writeln(*str_ptr);
    writeln(str_ptr[0][1]);

}

I thought that I am creating an array of pointers char [] *str_ptr so every single pointer will point to a single char. But it looks like str_ptr points to the start of the string str. I have to make a decision because if I am trying to give access to (for example) writeln(str_ptr[1]); I am getting a lot of information on console output. That means that I am linking to an element outside the boundary.

Could anybody explain if it's an array of pointers and if yes, how an array of pointers works in this case?


Solution

  • What you're trying to achieve is far more easily done: just index the char array itself. No need to go through explicit pointers.

    import std.stdio;
    import std.string;
    
    void main()
    {
        char [] str = "aaa".dup;
        str[0] = 'f';
        writeln(str[0]); // str[x] points to individual char
        writeln(str); // faa
    }
    

    An array in D already is a pointer on the inside - it consists of a pointer to its elements, and indexing it gets you to those individual elements. str[1] leads to the second char (remember, it starts at zero), exactly the same as *(str.ptr + 1). Indeed, the compiler generates that very code (though plus range bounds checking in D by default, so it aborts instead of giving you gibberish). The only note is that the array must access sequential elements in memory. This is T[] in D.

    An array of pointers might be used if they all the pointers go to various places, that are not necessarily in sequence. Maybe you want the first pointer to go to the last element, and the second pointer to to the first element. Or perhaps they are all allocated elements, like pointers to objects. The correct syntax for this in D is T*[] - read from right to left, "an array of pointers to T".

    A pointer to an array is pretty rare in D, it is T[]*, but you might use it when you need to update the length of some other array held by another function. For example

    int[] arr;
    int[]* ptr = &arr;
    (*ptr) ~= 1;
    assert(arr.length == 1);
    

    If ptr wasn't a pointer, the arr length would not be updated:

    int[] arr;
    int[] ptr = arr;
    ptr ~= 1;
    assert(arr.length == 1); // NOPE! fails, arr is still empty
    

    But pointers to arrays are about modifying the length of the array, or maybe pointing it to something entirely new and updating the original. It isn't necessary to share individual elements inside it.