char *Foo VS. char Bar[]

Lloyd Kremer kremer at cs.odu.edu
Sat Apr 15 02:27:51 AEST 1989



In article <19636 at iuvax.cs.indiana.edu> bobmon at 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



More information about the Comp.lang.c mailing list