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;
}

Output

    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.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.