Home » C programming language

What happens if we use an uninitialized array in C language?

Using an uninitialized array in C programming language: Here, we will learn that what happens if we use an uninitiated array in C language?
Submitted by IncludeHelp, on May 28, 2018

If we use any uninitialized array in C program, compiler will not generate any compilation and execution error i.e. program will compile and execute properly.

If the array is uninitialized while declaring and even after the declaration if you do not initialize then, you may get unpredictable result.

Therefore, it is recommended to write a good and safe program you should always initialize array elements with default values.

Consider the program:

#include <stdio.h>

int main(void) 
	int a[5];
	int b[5] = {0};
	int c[5] = {0,0,0,0,0};

	int i; //for loop counter

	//printing all alements of all arrays
	printf("\nArray a:\n");
	for( i=0; i<5; i++ )
		printf("arr[%d]: %d\n",i,a[i]);
	printf("\nArray b:\n");
	for( i=0; i<5; i++)
		printf("arr[%d]: %d\n",i,b[i]);
	printf("\nArray c:\n");
	for( i=0; i<5; i++ )
		printf("arr[%d]: %d\n",i, c[i]);
	return 0;


    Array a:
    arr[0]: -1948874610
    arr[1]: 32764
    arr[2]: 1249250789
    arr[3]: 11047
    arr[4]: 1

    Array b:
    arr[0]: 0
    arr[1]: 0
    arr[2]: 0
    arr[3]: 0
    arr[4]: 0

    Array c:
    arr[0]: 0
    arr[1]: 0
    arr[2]: 0
    arr[3]: 0
    arr[4]: 0

See the output, array a was uninitialized so the values are garbage while array b and c are initialized so the all element's values 0.

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.