Explain the concept of Uninitialized array accessing in C language



Problem

In C language, is the program executed, if we use an uninitialized array?

Solution

  • If we use any uninitialized array, compiler will not generate any compilation and an execution error.

  • If an array is uninitialized, you may get unpredictable result.

  • So, it’s better we should always initialize the array elements with default values.

Example Program

Following is the C program of accessing an uninitialized array −

 Live Demo

#include <stdio.h> int main(void){    int a[4];    int b[4] = {1};    int c[4] = {1,2,3,4};    int i; //for loop counter    //printing all alements of all arrays    printf("
Array a:
");    for( i=0; i<4; i++ )       printf("arr[%d]: %d
",i,a[i]);    printf("
Array b:
");    for( i=0; i<4; i++)       printf("arr[%d]: %d
",i,b[i]);    printf("
Array c:
");    for( i=0; i<4; i++ )       printf("arr[%d]: %d
",i, c[i]);    return 0; }

Output

When the above program is executed, it produces the following result −

Array a: arr[0]: 4195872 arr[1]: 0 arr[2]: 4195408 arr[3]: 0 Array b: arr[0]: 1 arr[1]: 0 arr[2]: 0 arr[3]: 0 Array c: arr[0]: 1 arr[1]: 2 arr[2]: 3 arr[3]: 4

Note

If we didn’t initialize an array, by default, it prints garbage values and never show an error.

Consider another C program for accessing an uninitialized array −

Example

 Live Demo

#include <stdio.h> int main(void){    int A[4];    int B[4] ;    int C[4] = {1,2};    int i; //for loop counter    //printing all alements of all arrays    printf("
Array a:
");    for( i=0; i<4; i++ )       printf("arr[%d]: %d
",i,A[i]);    printf("
Array b:
");    for( i=0; i<4; i++)       printf("arr[%d]: %d
",i,B[i]);    printf("
Array c:
");    for( i=0; i<4; i++ )       printf("arr[%d]: %d
",i, C[i]);    return 0; }

Output

When the above program is executed, it produces the following result −

Array a: arr[0]: 4195856 arr[1]: 0 arr[2]: 4195408 arr[3]: 0 Array b: arr[0]: -915120393 arr[1]: 32767 arr[2]: 0 arr[3]: 0 Array c: arr[0]: 1 arr[1]: 2 arr[2]: 0 arr[3]: 0
Updated on: 2021-03-09T09:48:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements