Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!wuarchive!udel!rochester!cornell!johnhlee From: johnhlee@CS.Cornell.EDU (John H. Lee) Newsgroups: comp.sys.amiga.programmer Subject: Re: ANOTHER SAS C BUG Message-ID: <1991Apr2.194634.27075@cs.cornell.edu> Date: 2 Apr 91 19:46:34 GMT References: <1991Mar31.035009.13183@csis.dit.csiro.au> <1991Apr1.050544.13878@cs.cornell.edu> <98@hdwr1.medar.com> Sender: news@cs.cornell.edu (USENET news user) Reply-To: johnhlee@cs.cornell.edu (John H. Lee) Organization: Cornell Univ. CS Dept, Ithaca NY 14853 Lines: 55 Nntp-Posting-Host: fulla.cs.cornell.edu In article <98@hdwr1.medar.com> jseymour@medar.com (James Seymour) writes: >John, you are correct in that what the original poster was complaining about >is, indeed, a portability "bug". You are incorrect regarding your comment >on how the string should be declared however (does this belong in the C >newsgroup?). > >char *str = "hello"; /* declare a pointer to a char array, > initialize pointer to a string */ > >char str[] = "hello"; /* declare a character array, initialized > in length and contents */ > >BIG difference. Especially if a function in another function is told >that str *contains* a pointer to char, when in reality it *is* the start >of the character array itself. [I've bitten myself with that one more times >than I'd care to count :-)]. Lastly, the amount of memory consumed is >not the same for each. The first declaration takes up more >memory than the second (although generally this is an insignificant >point). Which way it should be declared depends on what the program[mer] >needs. Yikes! Let me try again... I meant to say that the declaration should have been something like this: char buf[] = "hello"; char *str = buf; My point is that the declaration char *str = "hello"; declares a pointer to a string and sets its inital value to point to a string in memory. The string might be considered a "reusable constant" by the compiler and a use of the string elsewhere in the module like this: printf("hello"); could have it that the same string is used. Thus if you execute this: *str = 'i'; printf("hello"); you'll get "iello" printed out! This is by no means a certainty; page 104 of the second edition of K&R C says that the effect is undefined. By declaring a character array instead of a pointer, you are guarenteed to receive a private copy. As for my comment about the memory allocation being the same, I was off-base in the stated context, but should be right in the corrected context. ------------------------------------------------------------------------------- The DiskDoctor threatens the crew! Next time on AmigaDos: The Next Generation. John Lee Internet: johnhlee@cs.cornell.edu The above opinions of those of the user, and not of this machine.