What does Z["ack"] = 5 mean?

Earle R. Horton earleh at eleazar.dartmouth.edu
Wed Oct 5 23:57:28 AEST 1988


In article <14999 at agate.BERKELEY.EDU> laba-3aw at web.berkeley.edu 
	(Sam Shen) writes:
>Exactly what does this mean:
>
>main()
>{
>	char Z;
>
>	Z["ack!"] = 5;
>}
>

Portion of core dump obtained by running this program on a VAX, and core
dumping before main() returns, follows:

\300^C\214\350\377^?^E^@^@^@^Eck!^@^@^@

                            ^-- There's your 5!

What happened here was that Z was initialized to (char)0 by the
compiler or loader on the VAX.  (BSD 4.3)  Then, Z["ack!"] was taken
to mean 0["ack!"] which of course means 0[<address of "ack!">].  The
equivalence sets the first character in "ack!" equal to 5, which is
what you see in the core dump as displayed by emacs.

This is of course grossly implementation dependent, and uses
questionable programming practices, to wit:  Casting of char to
pointer is highly questionable.  Said pointer defaulting to (char *)
is probably reliable, but not good programming practice.  Assuming you
can write on top of constant data may not work on all systems.  The
assumption that Z will be equal to '\0' if not explicitly initialized
is not portable.  Worse, you cannot cast a pointer ("ack!") to an
integer array subscript on some systems!

Good programming practice demands you say exactly what you mean, and
only write on variable data (usually).  Thus:

main()
{
	char Z[5] = "ack!";

	Z[0] = 5;
}
Earle R. Horton. 23 Fletcher Circle, Hanover, NH 03755
(603) 643-4109
Sorry, no fancy stuff, since this program limits my .signature to three



More information about the Comp.lang.c mailing list