C programming hint

Bo Steinholtz bo at enea.UUCP
Sat Jul 13 06:09:05 AEST 1985


In article <899 at teddy.UUCP> kps at teddy.UUCP (Kesavan P. Srinivasan) writes:
>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 

Ah, how the heart of an old assembler language programmer rejoices!
For another description of this trick,
see e.g. the description of the MVC machine instruction in
"IBM System/360 Principles of Operation" from the sixties,
where it is pointed out that it may be employed to
initialize an array in one machine instruction.

However, the most authoritative (?) source on C,
Harbison/Steele: "C: A Reference Manual", Prentice-Hall 1984,
states in the definition of strncpy that:

	"The results are unpredictable if the two string
	arguments overlap in memory."

Thus, if strncpy is used, the trick is nonportable!



More information about the Comp.lang.c mailing list