Path: utzoo!utgpu!water!watmath!clyde!rutgers!sri-spam!ames!umd5!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Question about type casting Message-ID: <10187@mimsy.UUCP> Date: 15 Jan 88 04:16:24 GMT References: <5080009@hpfcdc.HP.COM> <5080010@hpfcdc.HP.COM> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 57 In article <5080010@hpfcdc.HP.COM> boemker@hpfcdc.HP.COM (Tim Boemker) writes: >... Consider int *A. If I know that A points to a 10x20 array, Given that declaration, A cannot point to a 10 x 20 array. It *can* point to the first element of the first row of such an array [see example below], from which all other element addresses can be computed; but it cannot point to the entire array. This is precisely the difference between a pointer to an object and a pointer to an array N of objects: only the latter points to the entire array. >I might like to address elements as A[i][j]. I can >do the indexing math myself, as in *(A + i * 20 + j), but that's not >what the question is really about. I want to know why a syntactically >correct and semantically meaningful expression is not allowed. Because, given the way C is defined, it is not semantically meaningful! One small (?) tweak---allow entire arrays to be rvalues---and it becomes meaningful, but it is not now so. >Why can't I cast an array as an array? Because rvalues cannot be arrays, and the result of a cast is an rvalue. Rvalues *can* be *pointers* to arrays: int *A, i, j; ... /* here we decide (by fiat or by analysis) that A points to the first element of X[10][20], i.e., A == &X[0][0], and then we set X[i][j] through A: */ ((int (*)[20])A)[i][j] = 1; ---although this has the limitation that all but the first dimension must be known at compile time, and again, this is precisely the same limitation as the one that exists for formal array parameters. -------- Note also that the cast replaces the first `array N of' with `pointer to'. This is the general rule that reduces arrays to pointers in C expressions (except as arguments to sizeof). If we decide that A points to the first element of `int Z[10]', and we want to set Z[5], we can write this: ((int (*))A)[5] = 999; but this reduces to ((int *)A)[5] = 999; or just A[5] = 999; so this is really rather boring. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris