Previous: 7.4 String Assignment and I/O
Up: 7 Arrays
Next: 7.6 Arrays for Databases
Previous Page: 7.4 String Assignment and I/O
Next Page: 7.6 Arrays for Databases
ANSI C allows automatic array variables to be initialized in declarations by constant initializers as we have seen we can do for scalar variables. These initializing expressions must be constant (known at compile time) values; expressions with identifiers or function calls may not be used in the initializers. The initializers are specified within braces and separated by commas. Here are some declarations with constant initializers:
int ex[10] = { 12, 23, 9, 17, 16, 49 };
char word[10] = { 'h', 'e', 'l', 'l', 'o', '\0' };
Each constant initializer in the braces is assigned, in sequence, to an element
of the array starting with index 0. If there are not enough initializers for
the whole array, the remaining elements of the array are initialized to zero.
Thus, ex[0] through ex[5] are assigned the values
12, 23, 9, 17, 16, and 49, while
ex[6] through ex[9] are initialized to zero.
Similarly, word is initialized to
a string "hello".
String initializers may be written as string constants instead of character
constants within braces, for example:
char mesg[] = "This is a message";
char name[20] = "John Doe";
In the case of mesg[],
enough memory is allocated to accommodate the string plus
a terminating NULL, and we do not need to specify the size of the array.
The above string initializers are allowed as a convenience,
the compiler initializes the array at compile time.
Remember, initializations are not
assignment statements; they are declarations that allocate and initialize
memory. As with other arrays, these array names cannot be used as
Lvalues in assignment statements.
Here is a short program that shows the use of initializers:
/* File: init.c
Program shows use of initializers for arrays.
*/
#include <stdio.h>
#define MAX 10
main()
{ int i, ex[MAX] = { 12, 23, 9, 17, 16, 49 };
char word[MAX] = {'S', 'm', 'i', 'l', 'e', '\0'};
char mesg[] = "Message of the day is: ";
printf("***Array Declarations with Initializers***\n\n");
printf("%s%s\n", mesg, word);
printf("Initialized Array:\n");
for (i= 0; i < MAX; i++)
printf("%d\n", ex[i]);
}
Sample Output: