0

In the below program I get garbage values for indexes like 2,4 etc

main()
{

    int j, arr[10] , a;
    int n = 10;
    while (n--)
    {
        scanf("%d", &a);
        printf("%d \n", ++arr[a]);
    }
}

output

9
0 
4
1781349929 
3
0 
2
395049983 
1
0

but when I increase the array initialized index to a large number every index value is assigned zero

main()
{

    int j, arr[10000] , a;
    int n = 10;
    while (n--)
    {
        scanf("%d", &a);
        printf("%d \n", ++arr[a]);
    }
}

output

    
9
0 
4
0 
3
0 
2
0 
1
0
prajwal
  • 7
  • 4
  • Because the array is uninitialized and so the program has undefined behavior. To initialize the array use `int arr[10]{};`. This is explained in any beginner level [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Aug 30 '22 at 04:44
  • Accessing unitialised values will get indeterminate values. If you want them to always be 0 it is your job to init to those values. – kaylum Aug 30 '22 at 04:44
  • If you look at your posted output, they aren't all 0 in either case. You never initialized the elements of either array. Using their values is undefined behavior. – Avi Berger Aug 30 '22 at 04:45

0 Answers0