string[] to char**

simendsjo simendsjo at gmail.com
Sat Mar 24 03:45:31 PDT 2012


On Sat, 24 Mar 2012 11:41:48 +0100, simendsjo <simendsjo at gmail.com> wrote:

> On Fri, 23 Mar 2012 17:09:18 +0100, bearophile  
> <bearophileHUGS at lycos.com> wrote:
>
>> On Friday, 23 March 2012 at 15:48:12 UTC, simendsjo wrote:
>>> What's the best way to convert char** from string[]?
>>
>> This is one way to do it:
>>
>>
>> import std.algorithm, std.array, std.string, core.stdc.stdio;
>> void main() {
>>      auto data = ["red", "yellow", "green"];
>>      immutable(char)** p = array(map!toStringz(data)).ptr;
>>      printf("%s %s %s\n", p[0], p[1], p[2]);
>> }
>>
>>
>> Note: the pointer array is managed by the D GC.
>>
>> With DMD 2.059:
>>
>> immutable(char)** p = data.map!toStringz().array().ptr;
>>
>> Bye,
>> bearophile
>
> Thanks. A lot shorter and safer than my current approach. I also expect  
> toStringz doesn't make a copy if \0 is at the end.
>
> For reference, my current approach was:
>
> auto strings = ["a", "b"];
> auto c_strings = cast(char**)malloc((char*).sizeof * strings.length);
> for(int i; i < strings.length; i++)
>    c_strings[i] = strings[i].ptr;

Oh, I didn't find toStringz, so I turned it into:

auto c_strings = strings.map!(toUTFz!(char*)).array().ptr;


More information about the Digitalmars-d-learn mailing list