What is wrong with this program?

Jeff Anton anton at ucbvax.ARPA
Sat Aug 17 04:20:33 AEST 1985


In article <353 at ttrdc.UUCP> levy at ttrdc.UUCP (Daniel R. Levy) writes:
>bruce at graffiti.UUCP (Bruce Jilek) <117 at graffiti.UUCP>:
>>
>>Why does printf insist that data->ut_line is a null string while
>>putchar can display all of the characters of this array?
>>...
>>	struct utmp {    /* This structure is straight out of utmp.h */
>>		char	ut_line[8];		/* tty name */
>>		char	ut_name[8];		/* user id */
>>		long	ut_time;		/* time on */
>>	};
>>...
>>			for (i = 0; i <= 7; i++) {
>>				putchar(data->ut_line[i]);
>>			}
>>			printf("\n");
>>			printf("%s	%s	%ld\n", data->ut_name,
>>				data->ut_line, data->ut_time);
/* how about */		printf("%.8s\t%.8s\t%ld\n", ....
>>...
>
>printf expects strings which are null-terminated at the end.  There is no
>guarantee that what you get in the arrays in struct utmp will be this way.
>Ergo, strange results.  Putchar is the way to go unless you want to copy
>the data out of the struct utmp into something which is null terminated for
>the sake of printf.
	Not really, you are forgetting that the format "%.8s" will
cause printf to print up to a null or 8 chars max.  Unfortunately
this style of printf can not be used with sizeof for compile time
format changes without run time code support.
-- 
C knows no bounds.
					Jeff Anton
					U.C.Berkeley
					ucbvax!anton
					anton at berkeley.ARPA



More information about the Comp.lang.c mailing list