Home > Net >  Why unintialized array elements are not 0 always in C
Why unintialized array elements are not 0 always in C

Time:07-25

I input 4566371 and find out that uninitialized array elements are not 0 as said in our texts


#include <stdio.h>
#define MAX 10

// Function to print the digit of
// number N
void printDigit(long long int N)
{
 // To store the digit
 // of the number N
 int array_unsorted[MAX];//array_unsorteday for storing the digits
 int i = 0;//initializing the loop for the first element of array_unsorted[]
 int j, r;

 // Till N becomes 0,we will MOD the Number N
 while (N != 0) {

     // Extract the right-most digit of N
     r = N % 10;

     // Put the digit in array_unsorted's i th element
     array_unsorted[i] = r;
     i  ;

     // Update N to N/10 to extract
     // next last digit
     N = N / 10;
 }

 // Print the digit of N by traversing
 // array_unsorted[] reverse
 for (j =MAX; j >=0; j--)
 {
     printf("%d ", array_unsorted[j]);
 }
}

// Driver Code
int main()
{
 long long int N;
 printf("Enter your number:");
 scanf("%lld",&N);
 printDigit(N);
 return 0;
}

output: Enter your number:4566371 77 0 8 32765 4 5 6 6 3 7 1
Process returned 0 (0x0) execution time : 2.406 s
Press any key to continue.
The other values should be o right?Why 77,0,32765 this way?Why not all are 0?like 0 0 0 0 4 5 6 6 3 7 1?

CodePudding user response:

An array of integers declared inside a function has unspecified values if it is uninitialized. If a similar array is declared at global scope, outside all functions, it will be initialized with zeros by default.

To make an array that is always initialized to zeros, do this:

int array_unsorted[MAX] = {};

This works because in C, = {0} will initialize all values with zero. If you say = {10, 20} it will initialize the first two elements as written, and the rest to zero.

CodePudding user response:

As noted in other answers, you may want to initialize your integer array. Whether or not you do that, you might want to replace the for loop statement conditions of:

for (j =MAX; j >=0; j--)

with:

for (j = i - 1; j >=0; j--) /* Start at the place the digit storage ended */

That way, you are not moving into array elements that were not used in the digit storage portion of your function.

Regards.

CodePudding user response:

You have correctly reserved a memory space for your array array_unsorted but the memory has not been cleaned before use. This memory reserved it was probably used by another program or variable before yours! This is why it already has some values in it. You should set it to 0 manually before starting to use it.

Hope it helps!

edit: used by another function or variable

  • Related