To Walter, about char[] initialization by FF

Derek Parnell derek at nomail.afraid.org
Wed Aug 2 00:12:30 PDT 2006


On Tue, 1 Aug 2006 23:45:26 -0700, Andrew Fedoniouk wrote:

>> But maybe that's because I never leave things at their defaults.  It's
>> like writing a story where you expect the reader to think everyone has 
>> brown eyes unless you say otherwise.
>>
> 
> Consider this:
> 
> char[6] buf;
> strncpy(buf, "1234567", 5);
> 
> What will be a content of you buffer?
> 
> Answer is: 12345\xff . Surprise? It is.

No, not surprised, just wondering why you didn't code it correctly though.

If you insist on using C functions then it should be coded ...

  extern(C) uint strncpy(ubyte *, ubyte *, uint );
  ubyte[6] buf;
  strncpy(buf.ptr, cast(ubyte*)"1234567", 5);


> In modern D reliable implementation of this shall be as:
> 
> char[6] buf; // memset(buf,0xFF,6); under the hood.
> uint n = strncpy(buf, "1234567", 5);
> buf[n] = 0;

Well that is debatable. I'd do it more like ...

 char[6] buf;  // An array of UTF-8 code units.
 uint n = strncpy(buf, "1234567", 5); // Replace the first 5 code-units.
 buf[n..$] = 0; // Set remaining code-units to zero.
 
> if you are going to use this with non D modules.
> 
> Needless to say that this is a bit redundant.
> 
> If D in any case initializes that memory why you need
> this uint n and buf[n] = 0; ?
> 
> Don't tell me please that this is because your spent
> your childhood in boyscout camps and got some high principles.
> Lets' put aside that matters - it is purely technical discussion.

Exactly. And technically you should be using ubyte[] and not char[].

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
2/08/2006 4:57:15 PM



More information about the Digitalmars-d mailing list