Path: utzoo!attcan!uunet!aplcen!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: typedef-ing an array Message-ID: <25247@mimsy.umd.edu> Date: 2 Jul 90 23:58:01 GMT References: <78627@srcsip.UUCP> <78633@srcsip.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 72 In article <78633@srcsip.UUCP> pclark@SRC.Honeywell.COM (Peter Clark) writes: >> ... typedef char foo[24]; ... >>Is there anyway to typedef an array (of a specific length)? Obviously, the >>above declaration doesn't do it, or I wouldn't be asking. ... The typedef above *does* do it. After typedef char foo[24]; `foo' is an alias for a type that is `array 24 of char' and has size 24*sizeof(char)==24. Thus, e.g., printf("%d\n", sizeof(foo)); must print 42. >What I meant was, why doesn't this work: >typedef char foo[29]; >/* a string with 28 chars, add one for the NULL byte */ >foo bar = "Hello World, this is my test"; >void > main() >{ > bar = "Silly old me"; > printf("%s\n",bar); >} >The initializer works fine, but the assignment inside main() doesn't. The first error is `void main': it must (yes must) be `int main', even if it never returns. It may have either 0 arguments or two (int argc, char *argv). The second, more important error is the assignment inside main. `bar' is an object of type `array 29 of char'; a quoted string is an object of type `array N of char' where N is one more than the number of characters in the string. `Silly old me' is 12 characters, so we have = ; The thing on the right hand side is in a value context, so it undergoes The Famous Rule [repeat: in any value context an object of type `array N of T' becomes a value of type `pointer to T' whose value is the address of the first (0th) element of the array]: = We now have a type mismatch---an array on the left and a pointer on the right---as well as another constraint violation: arrays are not modifiable lvalues and may not appear on the left of an assignment operator. One obvious way to change it runs into another problem: 1> int main() { 2> foo local = "Silly old me"; ... Now `local' is a local variable and the string on the right is an initializer. Line 2 here is NOT an executable statement, but rather a declaration with an initializer. Under ANSI C, aggregate initializers are always permitted provided that the initializer is constant (which this is). (The string on the right of the equal sign is not in a value context; it is in an initializer context.) If you hand this to a Classic C compiler, however, you will get a complaint, because Classic C allowed aggregate initializers only when the object being initialized was global or static. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@cs.umd.edu Path: uunet!mimsy!chris