Path: utzoo!utgpu!utstat!jarvis.csri.toronto.edu!mailrus!ukma!xanth!kremer From: kremer@cs.odu.edu (Lloyd Kremer) Newsgroups: comp.lang.c Subject: Re: char *Foo VS. char Bar[] Summary: string literals writeable? Message-ID: <8467@xanth.cs.odu.edu> Date: 14 Apr 89 16:27:51 GMT References: <19636@iuvax.cs.indiana.edu> Organization: Old Dominion University, Norfolk, Va. Lines: 36 In article <19636@iuvax.cs.indiana.edu> bobmon@iuvax.cs.indiana.edu (RAMontante) writes: >A student turned up a curious problem today >The essence of his code was > > char *foo = " "; > ... > sprintf(foo,"xxxx"); > >I had him change the declaration to > > char foo[6] = " "; /* assume I got the lengths correct */ In the first case, foo is a character pointer, initially set to point at a string literal. In the secon case, foo is an array of 6 chars, whose contents are initialized to 5 spaces followed by a '\0'. Note that the second case constitutes aggregate initialization, and hence requires that foo be of a global or static storage class. The statement is syntactically equivalent to int foo[6] = { 1, 2, 3, 4, 5, 0 }; In the second case, the contents of the array are always writeable. The question of whether the object to which foo points is writeable in the first case is the question, "Are string literals writeable?" Some compilers insist that they are, taking pains to place string literals in data space rather than constant space to accommodate it. Other compilers insist that they are not, and place them in protected space to enforce it. Lloyd Kremer Brooks Financial Systems {uunet,sun,...}!xanth!brooks!lloyd