Home > Article > Backend Development > Explain the concept of uninitialized array access in C language
In C language, if an uninitialized array is used, will the program be executed?
If we use any uninitialized array, the compiler will not generate any compilation and execution errors.
If the array is not initialized, you may get unpredictable results.
Therefore, it is better that we always initialize array elements with default values.
The following is a C program to access an uninitialized array -
Live demonstration
#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("</p><p>Array a:</p><p>"); for( i=0; i<4; i++ ) printf("arr[%d]: %d</p><p>",i,a[i]); printf("</p><p>Array b:</p><p>"); for( i=0; i<4; i++) printf("arr[%d]: %d</p><p>",i,b[i]); printf("</p><p>Array c:</p><p>"); for( i=0; i<4; i++ ) printf("arr[%d]: %d</p><p>",i, c[i]); return 0; }
When the above program is executed, the following results are produced -
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
If we do not initialize the array, by default, it will print garbage values and never show the error.
Consider another C program to access an uninitialized array -
Live demonstration
#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("</p><p>Array a:</p><p>"); for( i=0; i<4; i++ ) printf("arr[%d]: %d</p><p>",i,A[i]); printf("</p><p>Array b:</p><p>"); for( i=0; i<4; i++) printf("arr[%d]: %d</p><p>",i,B[i]); printf("</p><p>Array c:</p><p>"); for( i=0; i<4; i++ ) printf("arr[%d]: %d</p><p>",i, C[i]); return 0; }
When executing the above program, the following results will be produced -
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
The above is the detailed content of Explain the concept of uninitialized array access in C language. For more information, please follow other related articles on the PHP Chinese website!