Path: utzoo!utgpu!watmath!att!pacbell!ames!purdue!haven!decuac!shlump.nac.dec.com!mountn.dec.com!minow From: minow@mountn.dec.com (Martin Minow) Newsgroups: comp.sys.mac.programmer Subject: Re: Seemingly equivalent code fragments in C Keywords: C pointers Lightspeed int Message-ID: <559@mountn.dec.com> Date: 7 Aug 89 20:53:36 GMT References: <4882@tank.uchicago.edu> Reply-To: minow%thundr.dec@decwrl.dec.com (Martin Minow) Organization: Digital Equipment Corporation Lines: 49 In article <4882@tank.uchicago.edu> s170@tank.uchicago.edu (harmon g washington) tries to create a Pascal string: > int *bittenApple; > > *bittenApple = 0x0114; /* create Pascal string 1 byte long */ > AppleMenu = NewMenu(ApplID, bittenApple); >THIS CODE DID NOT WORK! Instead of the Apple logo I got a random string of junkIt seemed it should have work: defining a pointer to an int; and then defining the item it points to. Now the following fragment of code DID work: This code sequence has the following meaning: int *bittenApple; This is a pointer to a default-sized integer. (It will point to a 16-bit integer on Think-C, but you cannot count on that.) *bittenApple = 0x0114; The current value of bittenApple (whatever it is) is the address of an integer. Store 0x0114 in that location. This writes 0x0114 in a random location in memory. ... NewMenu(ApplID, bittenApple); Pass the random location in bittenApple to NewMenu. Note that bittenApple was never initialized and a garbage value was passed to NewMenu (This could be the address of ROM, or a location on the stack that is overwritten). The second example corrects this: > int *bittenApple, xx; > xx = 0x0114; Store 0x0114 in xx. > bittenApple = &xx; Store the address of xx in bittenApple > AppleMenu = NewMenu(ApplID, bittenApple); There is one further, in some ways more serious, problem: an integer containing the value 0x0114 is *not* necessarily equivalent to a string. (There are a number of subtle C-language points here that would be better explained in a C textbook.) A better way to perform the function in Think C would be: AppleMenu = NewMenu(ApplID, "\p\024"); Here "\p" introduces a Pascal format string. (This is not compatible with other C's) and \024 is the octal equivalent of \x14. A more compatible method would be: char bittenApple[] = { 0x01, 0x14 }; AppleMenu = NewMenu(ApplID, &bittenApple[0]); The last example should work anywhere. Hope this clarifies the problem. Martin Minow minow%thundr.dec@decwrl.dec.com