string assignment in C

Daniel R. Levy levy at ttrdc.UUCP
Sun Oct 16 13:26:42 AEST 1988


In article <6777 at chinet.chi.il.us>, john at chinet.chi.il.us (John Mundt) writes:
> char p[] = { 't','h','i','s',' ','a',' ','s','t','r','i','n','g','\n' };
> 
> main()
> {
> 	printf(p);
> }

Be careful with this kind of declaration: without the terminating '\0' there
is no guarantee where the "string" p[] ends.  In fact, try this on a vax, 3b,
or machine of similar architecture:

char p[] = { 't','h','i','s',' ','a',' ','s','t','r','i','n','g',' ',
	     ' ','\n' };	/* 16 bytes, NO NULL TERMINATOR */
char q[] = { 't','h','i','s',' ','g','a','r','b','a','g','e','\n','\0' };

main()
{
	printf(p);
}

The output of the program will be:

this a string  
this garbage

The 16 bytes in p[] is to make it end just before the word boundary on which
q[] begins.  Otherwise the system will probably pad p[] with nulls and you
won't notice the lack of explicit null terminator.
-- 
|------------Dan Levy------------|  THE OPINIONS EXPRESSED HEREIN ARE MINE ONLY
| Bell Labs Area 61 (R.I.P., TTY)|  AND ARE NOT TO BE IMPUTED TO AT&T.
|        Skokie, Illinois        | 
|-----Path:  att!ttbcad!levy-----|



More information about the Comp.lang.c mailing list