What is Incomplete Initialization in C Programming?

This C Tutorial Explains Incomplete Initialization in C Programming with Example(s).

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,

advertisement
advertisement
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,

Note: Join free Sanfoundry classes at Telegram or Youtube
/*
 * 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.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.