dynamic array of strings

Michael P. baseball.mjp at gmail.com
Tue Dec 30 11:14:09 PST 2008


>Well, let's go through the code.
> 
> First of all, you should undestand that an array is nothing but a pair of pointer to first element and its length.
> 
> Since char[] == string in D1, let's use string instead to make code slightly more readable.
> 
> string[] names; // array of strings that will store our names
> string currentName;
> ...
> din.readf( "%s", &currentName ); // what does this line do?
> 
> din.readf tries to minimize allocations by accepting a buffer where the string will be stored. Buffer will be allocated on heap if provided one is too small to fit the whole string.
> 
> Initially, currentName is null, i.e. currentName.ptr is null and currentName.length == 0. If you type anything, the data won't fit into buffer and therefore a new one is created by readf. When you return from readf, currentName will point to "michael" and have length == 7.
> 
> When you call din.readf for second time, you pass your currentName as a buffer once again. This time it is large enough to fit "is" and therefore it is not reallocated. "is" is written on top of "michael" and becomes "ischael". currentName's length is updated to 2. Etc.
> 
> Here is names' contents step by step:
> 
> At Startup:
> string[] names = []; // empty
> 
> Step 1:
> string[] names = [ "michael" ];
> 
> Step 2:
> string[] names = [ "ischael", "is" ];
> 
> Step 3:
> string[] names = [ "coolael", "co", "cool" ];
> 
> Step 4:
> string[] names = [ "stopael", "st", "stop", "stop" ];
> 
> When you reset buffer (by doing "currentName = null;"), a new one is allocated each step and each string gets its own memory. That's it.

So, the strings that are in the array(names) are pointers to the same buffer? And if you set it to null each time, then a new buffer for each string is created instead of being overwritten?
Makes sense now, thanks.
-Micheal P.



More information about the Digitalmars-d-learn mailing list