分类: C/C++
2007-11-13 17:18:23
< Day Day Up > |
Fancy DeclarationsC enables you to create elaborate data forms. Although we are sticking to simpler forms, we feel it is our duty to point out the potentialities. When you make a declaration, the name (or identifier) can be modified by tacking on a modifier.
C enables you to use more than one modifier at a time, and that enables you to create a variety of types, as shown in the following examples: int board[8][8]; // an array of arrays of int int ** ptr; // a pointer to a pointer to int int * risks[10]; // a 10-element array of pointers to int int (* rusks)[10]; // a pointer to an array of 10 ints int * oof[3][4]; // a 3 x 4 array of pointers to int int (* uuf)[3][4]; // a pointer to a 3 x 4 array of ints int (* uof[3])[4]; // a 3-element array of pointers to 4-element arrays of int The trick to unraveling these declarations is figuring out the order in which to apply the modifiers. These rules should get you through:
Let's apply these rules to this declaration: int * oof[3][4]; The [3] has higher precedence than the *, and, because of the left-to-right rule, it has higher precedence than the [4]. Hence, oof is an array with three elements. Next in order is [4], so the elements of oof are arrays of four elements. The * tells us that these elements are pointers. The int completes the picture: oof is a three-element array of four-element arrays of pointers to int, or, for short, a 3x4 array of pointers to int. Storage is set aside for 12 pointers. Now look at this declaration: int (* uuf)[3][4]; The parentheses cause the * modifier to have first priority, making uuf a pointer to a 3x4 array of ints. Storage is set aside for a single pointer. These rules also yield the following types: char * fump(); // function returning pointer to char char (* frump)(); // pointer to a function that returns type char char (* flump[3])();// array of 3 pointers to functions that // return type char You can use typedef to build a sequence of related types: typdef int arr5[5]; typedef arr5 * p_arr5; typedef p_arr5 arrp10[10]; arr5 togs; // togs an array of 5 int p_arr5 p2; // p2 a pointer to an array of 5 int arrp10 ap; // ap an array of 10 pointers to array-of-5-int When you bring structures into the picture, the possibilities for declarations truly grow baroque. And the applications… well, we'll leave that for more advanced texts. |
< Day Day Up > |