Date: Wed, 24 Sep 1997 14:47:48 -0400 (EDT) From: "Art S. Kagel" To: "Peter J. Farley III" Cc: djgpp AT delorie DOT com Subject: Re: Problem with strncpy (DJGPP in msdos window in win95) In-Reply-To: <342864fb.2276250@snews.zippo.com> Message-Id: Mime-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Precedence: bulk On Wed, 24 Sep 1997, Peter J. Farley III wrote: > "Paul Fitzgibbons" wrote: > > >I have a problem with the following code. When inputting strings of up to 20 > >chars there doesnt appear to be a problem but if i input a string of length > >21 or greater the string then ends in funny characters. I thought strncpy > >would have avoided this? I am able to write a function to check if the > >length is greater and to loop if it is, but i would rather do it by > >shortening the string. > > > >Any help will be much appreciated. > > Paul, > > You forgot to terminate the string. IIRC, strncpy() does not > terminate with a null after the "n" characters are copied. Try this > (see my added comments). Output examples following the code. Almost, strncpy copies up to n characters including any NULL that it finds in those first n characters and then pads the target string with NULLS to 'n' characters (I have a friend who uses strncpy("",mystr,20) to initialize string spaces to NULLs, slower than memset() but he has fun...). So, just as Paul noticed, if the source string is longer than 'n' characters the target is not NULL terminated. Peter's recommended code is correct, very standard (I do it that way myself), and very efficient (the, perhaps unneccessary assignment is a lot cheaper than the test that could eliminate it). Art S. Kagel, kagel AT bloomberg DOT com