Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!usc!ucsd!ucbvax!dewey.soe.berkeley.edu!oster From: oster@dewey.soe.berkeley.edu (David Phillip Oster) Newsgroups: comp.sys.mac.programmer Subject: Re: String Copy in THINK C 4.0 Message-ID: <34105@ucbvax.BERKELEY.EDU> Date: 4 Feb 90 04:21:17 GMT References: <2083@quiche.cs.mcgill.ca> <2826@draken.nada.kth.se> Sender: usenet@ucbvax.BERKELEY.EDU Reply-To: oster@dewey.soe.berkeley.edu.UUCP (David Phillip Oster) Organization: School of Education, UC-Berkeley Lines: 34 In article <2826@draken.nada.kth.se> d88-jwa@nada.kth.se (Jon W{tte) writes: >memmove(p2, p1, *p1 + 1); /* copies pascal string p1 to p2 */ ^ This is NOT the right way to get the length of a pascal string. I've has subtle bugs happen on long strings. Many people say, but pascal strings are unsigned chars, so the zeroth one is already in the range 0..255, isn't that right? Well, it is, until you try to calculate with them. For exmaple, suppose you do the following: StringPtr p = (StringPtr) ""; now, what is *p - 1? The answer: 0xFFFF. If you say (long) (*p - 1), you get 0x0000FFFFL because of C's promotion rules for expressions involving unsigned operands. The right way to take the length of a pascal string is: #define Length(s) ((short) (unsigned char) (s)[0]) The second cast forces the result to be a signed integer in the range 0..255. Now, (long) (Length(p) - 1) is -1L, as it should be. Write it right, and you only have to write it once. > The mac is a detour in the inevitable march of mediocre computers. > drs@bnlux0.bnl.gov (David R. Stampf) --- David Phillip Oster -master of the ad hoc odd hack. Arpa: oster@dewey.soe.berkeley.edu Uucp: {uwvax,decvax}!ucbvax!oster%dewey.soe.berkeley.edu