Next: Arguments with main() Up: Arrays and Pointers Previous: Multi-dimensional arrays

Initializing variables and arrays

Simple variables can be initialized when they are defined:

   int count=2;
   double mean= 0.5;

Arrays can also be initialised but ANSI differs from many earlier compilers. Many early compilers forbid initialising automatic arrays. ANSI C allows any array to be initialised.

Static variables (whether simple or arrays) are initialised only once.

Automatic variables are initialised whenever they are created.

To initialise an array, the syntax is, for example:

   static int name[4]= { 10, 20, 30, 40 };

This has the effect of setting name[0] to be 10 etc.

For a two-dimensional array, use, for example:

static int name[2][4]=
   {
      {10,20,30,40}   /* name[0][0-3] */
      {50,60,70,80}   /* name[1][0-3] */
   }

There is a special shorthand for initializing character arrays (but not for assignment where strcpy() should be used):

   char pattern[]= "the";

creates pattern[4] with the string "the" (null-terminated) loaded in it.



Next: Arguments with main() Up: Arrays and Pointers Previous: Multi-dimensional arrays


maspjw@
Tue Sep 27 15:29:34 BST 1994