A question...

Shiping Zhang ping at cubmol.BIO.COLUMBIA.EDU
Thu Aug 17 05:31:22 AEST 1989


In article <1586 at sunset.MATH.UCLA.EDU> tony at MATH.UCLA.EDU () writes:
>Hello netland:
>
>I seemed to have run into a strange problem in C that I can't quite 
>figure out.
>
>I'm just trying to convert a time value stored in a long integer 
>in the form 111753 into a more presentable format 11:17:53.
>
>The variables were declared as follows:
>
>	long        call_time ;
>	char        str_time[21],   local_str[21] ;
>
>In a while loop I got the data and did the following:
>
>	sprintf (local_str,"%06ld",call_time) ;
>	strncpy (str_time,local_str,2) ;
>	strcat  (str_time,":") ;
>	strncat (str_time,&local_str[2],2) ;
>	strcat  (str_time,":") ;
>	strncat (str_time,&local_str[4],2) ;
>	str_time[8]='\0' ;
>
>	fprintf (fp,"%s time = %06ld local_str = %s str_time = %s\n",
>			 	str_date,call_time,local_str,str_time) ;
>
Add the following line after strncpy() will fix the problem:

        str_time[2]='\0';

strcat and strncat append a copy of the second argument to the END of
the first argument, that means the appending begins at the NULL
character. strncpy() does not null-terminate str_time here
because the length of local_str is longer than 2. strncpy worked ok for
the first time because str_time was initiated to null for all
its members. But after the first round of the loop, str_time is filled
with non-null characters upto the 9th position WHERE strcat() and
strncat always begin appending. Then str_time[8]='\0' simply
cuts off what they have appended. That is why only the first two 
characters are changed.

-ping



More information about the Comp.lang.c mailing list