How to use sprintf

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 26 10:15:16 PDT 2011


On Tue, 26 Apr 2011 10:08:21 -0400, Alexander <aldem+dmars at nk7.net> wrote:

> On 26.04.2011 15:21, Daniel Gibson wrote:
>
>> No, in D arrays are not just pointers. It's indeed a struct that
>> contains the length (arr.length) and the pointer (arr.ptr).
>
>   If this is a struct, then there is no "special compiler handling"  
> needed to cast a struct to a pointer using opCast() (except for static  
> arrays).
>
>   But, from programmer point of view, array is not a struct, just a type  
> with some properties, "struct" is hidden somewhere internally.

A "struct" is simply a group of members used as data, and a group of  
functions that accept that member as the first parameter.  The same is  
true for arrays, although it's not defined anywhere as a "struct."

Arrays are special types to the compiler, they are not ordinary  
structures.  However, more and more they are being extended in the  
library.  In reality, they could just be treated as normal types with the  
library defining the properties, thanks to the ability to add array  
properties.  Already associative arrays are done that way.  The way it is  
implemented is a mix between newer style functions defined in the library  
and original functions that were done way back when D did not have the  
ability to add array properties.

>
>> This makes arrays in D a lot safer and also easier to use than in C.
>
>   I see no danger in using cast(void *)Array instead of Array.ptr, if  
> semantic is known in advance (and it is).

Casting overrides the type system.  It's always a red flag.

Example:

void foo()
{
char[] buffer = new char[12];

...

auto charptr = cast(char *)buffer;

sometime down the road, you decide buffer should be a const input  
parameter:

void foo(const(char)[] buffer)
{
...

auto charptr = cast(char *)buffer; // oops! there goes const!

or if you decide later to use wchar[], or whatever.  casting says "I know  
what I'm doing" and should be only used very sparingly.  It should not be  
a tool of first resort.

compare that to:

char *charptr = buffer.ptr; // throws an error if buffer is not a char[]

or even more robust:

auto charptr = buffer.ptr; // now all your code is upgraded to use the  
newest type you decide on.

In other words, casting an array to a pointer is first of all a hack, and  
second of all 100% unnecessary.  It's just wasting compiler code space.

-Steve


More information about the Digitalmars-d mailing list