www.digitalmars.com         C & C++   DMDScript  

D - how does printf("hello") work?

reply Kimberley Burchett <kimbly at kimbly.com> <Kimberley_member pathlink.com> writes:
The documentation says that strings are not zero-terminated, and so you need to
call append(0) to zero-terminate them before passing them to C functions.  But
then it goes on to give this example:

str.append(0);
printf("the string is '%s'\n", (char *)str);

So what's up with passing the format string directly to printf, without
appending a zero?
Jan 15 2003
parent reply Russell Lewis <spamhole-2001-07-16 deming-os.org> writes:
Kimberley Burchett  wrote:
 The documentation says that strings are not zero-terminated, and so you need to
 call append(0) to zero-terminate them before passing them to C functions.  But
 then it goes on to give this example:
 
 str.append(0);
 printf("the string is '%s'\n", (char *)str);
 
 So what's up with passing the format string directly to printf, without
 appending a zero?
 
 

When you give a constant string in D (like the format string you mentioned), D allocates a null terminator in the memory, even though the array doesn't stretch to include that character. That is, when low-level C routines look at the memory, they will see the null terminator, even though it doesn't show up in the .length of any D array. This is not the case, of course, for any dynamically generated string. You have to append to those. A very perceptive question. I hope that my answer makes sense.
Jan 15 2003
parent "Walter" <walter digitalmars.com> writes:
"Russell Lewis" <spamhole-2001-07-16 deming-os.org> wrote in message
news:3E258C2A.9040902 deming-os.org...
 A very perceptive question.  I hope that my answer makes sense.

Yes, it is a very good question, and your answer was spot on.
Jan 15 2003