If I leave some integer array items uninitialized I get sometime some strange numbers instead of zeros when I display the list of the array items.
Why is it happening?
Thank you.

Short answer: Because you're leaving the elements in the array uninitialized.

Long answer:
Consider the following code snippet.

int foo[10];

int main( void )
{
    static int bar[10];
    int gus[10];
    int i;    

    for ( i = 0; i < 10; i++ )
    {
        printf( "%d %d %d\n", foo[i], bar[i], gus[i] );
    }

    return 0;
}

If you run this code, every element in foo and bar will be 0, where gus's vars are random garbage. This is because of where the memory for the arrays are being allocated.

'foo' and 'bar' are both being allocated in static storage. Arrays declared as static are pre-initialized to 0 because this space is allocated when the program is first loaded into memory. 'gus', on the other hand is located in automatic storage, AKA, on the runtime stack. This space isn't allocated until the program starts running, and when the 'main' method is invoked and pushed on the stack.

When automatic variables are allocated, all the program does is grab the memory and whatever garbage is already in there. You know, in the interest of speed and stuff.

commented: Simple answer +10

if you try to print value of any uninitialized variable c compiler assigns garbage value and prints it so its always better to check whether you have initialized all the elements in your program or not
and as for the answer to your question... IsharaComix has given exact answer
and you can also initialize array elements when you declare the array. so the use of for loop is unnecessary whenever there is no need for run-time inputs from user.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.