string assignment in C

John Mundt john at chinet.chi.il.us
Thu Oct 13 10:09:16 AEST 1988


In article <1988Oct11.143728.28627 at gpu.utcs.toronto.edu> romwa at gpu.utcs.toronto.edu (Mark Dornfeld) writes:
>	char *p1="first";
>	char *p2;
>	main(  )
>	{
>	  p2 = " is:";
>	}
>Isn't the assignment of p2 a dangerous thing to
>do since the compiler has (presumably) only left enough space
>for the pointer and not for the string.


The two are the same.  Each is a pointer to char.  Each string, 
"first" and " is:" are reserved by the compiler as unnamed strings 
somewhere in memory.  Both p1 and p2 are pointers who are set to point
to these strings.  You could reassign p1 or p2 to any other string as
well.   In other words, you could say p1 = p2 or p2 = (char *) 0.
Try running sizeof() on either of them and both will return 
an integer equal to  sizeof(char *).  

Now, this would be different:

char p[] = { 't','h','i','s',' ','a',' ','s','t','r','i','n','g','\n' };

main()
{
	printf(p);
}

Here, p is a fixed array of characters and cannot be reassigned.
Trying to say p = (char *) 0 would be illegal.

Further, sizeof(p) would be the length of the string "this is a
string\n" rather than the size of a character pointer.
-- 
---------------------
John Mundt   Teachers' Aide, Inc.  P.O. Box 1666  Highland Park, IL
(312) 432-8860	-998-5007 Voice  ||  -432-5386 Modem  



More information about the Comp.lang.c mailing list