C programming hint
Marcus Hand
mgh at mtunh.UUCP
Fri Jul 12 06:47:12 AEST 1985
> Reply-To: kps at teddy.UUCP (Kesavan P. Srinivasan)
> Keywords: strncpy
> Summary: initializing strings (arrays of characters)
>
> I found a way to initialize an array of characters without using a loop.
> Here is the method I used:
>
> char blanks[SIZE]; /* declare array of SIZE elements */
>
> blanks[0] = ' '; /* initialize 1st element */
>
> strncpy(blanks + 1, blanks, SIZE - 1); /* initialize entire array */
> ^^^ ^^^ ^^^
> | | |
> destination source how many characters to copy
>
> The trick is to use strncpy in an almost recursive way.
> Well, I hope you found this useful.
Sorry to dissapoint you, but
1. strncpy() is implemented using a loop (this side effect
wouldn't work if it wasn't);
2. it only works if strncpy is implemented by starting with the
first character to be moved and not the last (you can move
up and down a string in either direction). I.e. it's
implementation dependent;
3. its not recursive or even analogous to recursion -- it just
keeps copying the last character it moved;
4. whats wrong with memset() (memory(3)) -- I don't know
whether its any more efficient, but its certainly
clearer to the reader what you are trying to achieve,
and safer because its not implementation dependant:
rtn = memset (buffer, ' ', buflen);
Hope this helps you.
--
Marcus Hand (mtunh!mgh)
More information about the Comp.lang.c
mailing list