> initializing arrays in c ~ Online tutorial

initializing arrays in c

Initializing Arrays
Arrays can be initialized in two ways. The first way is by assigning every element to some value with a statement like:
array[2] = 42;
array[3] = 12;

or perhaps with the aid of one or more for loops. Because it is tedious, to say the least, not to mention uneconomical, to initialize the values of each element to as different value, C provides another method, which employs a single assignment operator = and curly braces { }. This method only works for static variables and external variables.
Recall that arrays are stored row-wise or with the last index varying fastest. A 3 by 3 array could be initialized in the following way:
static int array[3][3] =


The internal braces are unnecessary, but help to distinguish the rows from the columns. The same thing could be written:
int array[3][3] =


Take care to include the semicolon at the end of the curly brace which closes the assignment.
Note that, if there are not enough elements in the curly braces to account for every single element in an array, the remaining elements will be filled out with zeros. Static variables are always guaranteed to be initialized to zero anyway, whereas auto or local variables are guaranteed to be garbage: this is because static storage is created by the compiler in the body of a program, whereas auto or local storage is created at run time.

Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
Powered By: BloggerYard.Com