Path: utzoo!utgpu!water!watmath!clyde!mcdchg!chinet!john From: john@chinet.chi.il.us (John Mundt) Newsgroups: comp.lang.c Subject: Re: string assignment in C Message-ID: <6777@chinet.chi.il.us> Date: 13 Oct 88 00:09:16 GMT References: <1988Oct11.143728.28627@gpu.utcs.toronto.edu> Reply-To: john@chinet.chi.il.us (John Mundt) Organization: Chinet - Public Access Unix Lines: 38 In article <1988Oct11.143728.28627@gpu.utcs.toronto.edu> romwa@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