Explain the concept of Uninitialized array accessing in C language

CServer Side ProgrammingProgramming

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("\nArray a:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i,a[i]);
   printf("\nArray b:\n");
   for( i=0; i<4; i++)
      printf("arr[%d]: %d\n",i,b[i]);
   printf("\nArray c:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",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("\nArray a:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i,A[i]);
   printf("\nArray b:\n");
   for( i=0; i<4; i++)
      printf("arr[%d]: %d\n",i,B[i]);
   printf("\nArray c:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",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
raja
Published on 09-Mar-2021 08:30:42
Advertisements