Search code examples
carraysc-stringsgarbage

Is it mandatory to assign default value zero to integer array in C?


I am implementing program to count frequency of digits in alphanumeric string, but after spending hours with weird output I am able to find solution that C is setting garbage value to all index values. But surprise for me is that compiler setting some values to zero(in my example it is setting 0 for 0 to 7 index, and some random garbage value at 8th and 9th position). Still, after searching around so much and discussion with colleague, I am not find any solution.

Here I am posting my code and output.

#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_LENGTH  1000

int main()
{
    int ar[10];

    char s[MAX_LENGTH];
    scanf("%s",s);

    for(int i = 0; i < strlen(s); i++){
        int index = s[i] - 48;
        if(index >= 0 && index <= 9){
            ar[index] = ar[index] + 1;
        }
    }

    for(int i = 0; i <= 9; i++){
        printf("%d \n", ar[i]);
    }
}

Input : as12556fsd889ad9

From debugger I am getting this snap shot : debugger snap shot

Output :

0 
1 
1 
0 
0 
2 
1 
0 
1606415986 
32769

Why compiler setting garbage value 0 from index 0 to 7 and 1606415986 at index 8 and 32769 at index 9.

Any help or link which give me deep understanding for this would be appreciated.

I am beginner and student so please do not down vote my question. Thanks


Solution

  • int ar[10]; inside a function does not initialize the elements to 0. ar is uninitialized.

    The value of the elements of ar[] are indeterminate. @haccks

    The compiler may set them to 0, may set them to "garbage", stop code if accessed and it contains a trap value, or many others possibilities. The most likely scenario is that the values are whatever happens to be in memory.

    The point is that good code should first initialize them or assign them, before reading them.

    // char s[MAX_LENGTH];
    char s[MAX_LENGTH] = { 0 };