C programming hint

Guy Harris guy at sun.uucp
Fri Jul 12 16:28:07 AEST 1985


> I found a way to initialize an array of characters without using a loop. ...
> 	strncpy(blanks + 1, blanks, SIZE - 1);	/* initialize entire array */

Ummm... there *is* a loop there; it just happens to be hidden in the
"strncpy" routine.  In some C libraries on some machines, this uses a faster
sequence to copy the data than the fastest C loop.  On other machines,
"strncpy" is just the obvious C loop (and you pay the overhead of a
subroutine call).  On other machines, "strncpy" might not work with
overlapped strings...

The System V C library has a routine called "memset" which can be used to
set a block of bytes to a specific value.  Modulo the subroutine call
overhead, this is probably the most efficent way of initializing the array
(the "strncpy" has to fetch byte N to move it to byte N+1; the "memset" can
keep that byte in a register).

	Guy Harris



More information about the Comp.lang.c mailing list