Let’s consider examples of incomplete initialization below,
int jams[5] = {1, 2, 3, 4, 5, 6}; int hats[5] = {1, 2, 3, 4};
Notice that ‘jams’ is an array of 5 integers while we are trying to pack it with 6 integers. What will happen then? Let’s explore,
/* * arr_with_more_ele_than_size.c -- program shows can an array be * initialized with more elements than its size */ #include <stdio.h> int main(void) { int i; int jams[5] = {1, 2, 3, 4, 5, 6}; for (i = 0; i < 6; i++) printf("jams[%d] is %d\n", i, jams[i]); return 0; }
Now, we observe the output below,
arr_with_more_elements_than_size.c:7:2: warning: excess elements in array initializer [enabled by default] arr_with_more_elements_than_size.c:7:2: warning: (near initialization for ‘jams’) [enabled by default] [root@localhost kar_arrays]# ./a.out jams[0] is 1 jams[1] is 2 jams[2] is 3 jams[3] is 4 jams[4] is 5 jams[5] is 32767
Well! When we tried to pack into array ‘jams’ more elements than its size, it didn’t and issued instead a warning “more elements in the array initializer”.
Now, let’s turn to other side of coin; consider an array with less elements than its size, below,
/* * arr_with_less_elem_than_size.c -- program shows can an array be * initialized with less elements than its size */ #include <stdio.h> int main(void) { int i; int hats[5] = {1,2,3,4}; for (i = 0; i < 5; i++) printf("hats[%d] is %d\n", i, hats[i]); return 0; }
Observe the output below,
[root@localhost kar_arrays]# ./a.out hats[0] is 1 hats[1] is 2 hats[2] is 3 hats[3] is 4 hats[4] is 0
Notice that if an array, for ex. hats[5], contains less no. of initializers, at least one, in the list than its size, initializers are assigned sequentially from index 0 through till last initializer is assigned. Rest of the elements are assigned to 0 automatically.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for C Internship
- Apply for Computer Science Internship
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Check C Books