strings no longer writable?

Blair P. Houghton bhoughto at cmdnfs.intel.com
Tue Oct 30 10:26:43 AEST 1990


In article <1990Oct29.174410.28498 at batcomputer.tn.cornell.edu> lijewski at theory.tn.cornell.edu (Mike Lijewski) writes:
>
>My understanding is that strings are no longer writable.  That is to say,
>the assignment to s[5] in the below program shouldn't be allowed.
>
>main() { char *s = "testing"; s[5] = 'z'; }

Correct.

However, if you had done

	main() { char s[] = "testing"; s[5] = 'z'; }

s would itself be an array and be writable; it is considered
identical to having done

	main() { char s[] = {'t','e','s','t','i','n','g','\0'}; s[5] = 'z'; }

(cf. ANSI X3.159-1989, sec. 3.5.7, p. 75, ll. 24-30)

>Is a conforming implementation required to issue a warning, an error, or
>what?

"...the declaration

    char *p = "abc";

defines p with type `pointer to char' that is initialized
to point to an object with type `array of char' with length
4 whose elements are initialized with a character string
literal.  If an attempt is made to use p to modify the
contents of the array, the behavior is undefined."
(ibid., ll. 30-34)

Therefore, it's entirely up to your implementor.

				--Blair
				  "Harder to find than to understand..."



More information about the Comp.std.c mailing list