While I was programming, I encountered an strange behaviour of printf, please look at the 3 consecutive printfs below:
/*Program to find the number of digits which divides the given number with rem = 0.*/
#include<stdio.h>
//int arr_fun(int );
/*Function for storing digits of a number into
an array and find its length*/
int *arr_fun(int n, int *len)
{
int arr[100] = {0};
int i;
//(*len) = 0;
for(i = 0; n != 0;i++)
{
arr[i] = n%10;
n = n/10;
(*len) = (*len) + 1;
}
return arr;
}
int main()
{
int n = 0, t = 0, len = 0;
int i = 0, j = 0, count = 0;
int *arr_new = NULL;
arr_new = (int *)calloc(100, sizeof(int));
if(NULL == arr_new)
{
printf("Memory allocation failed.\n");
return -1;
}
scanf("%d",&t);
if(1 <= t && t <= 15)
{
for(i = 0; i < t; i++)
{
scanf("%d", &n);
len = 0;
arr_new = arr_fun(n, &len);
//These 3 printfs:
printf("\nlength = %d, arr_new[0] = %d, arr_new[1] = %d\n", len, arr_new[0], arr_new[1]);
printf("\nlength = %d, arr_new[0] = %d, arr_new[1] = %d\n", len, *arr_new, *(arr_new+1));
printf("\nlength = %d, arr_new[0] = %d, arr_new[1] = %d\n", len, arr_new[0], arr_new[1]);
// for(j = 0; j < len; j++)
// {
printf("\nlen = %d, arr_new[%d] = %d \n", len, j, arr_new[0]);
//}
/*
for(j = 0; j < len; j++)
{
if((n % arr_new[j]) == 0)
{
count++;
}
}
printf("\n%d\n", count);
*/ }
}
return 0;
}
Sample input 1 23
Output: length = 2, arr_new[0] = 2, arr_new[1] = 3
length = 2, arr_new[0] = 0, arr_new[1] = 4104
length = 2, arr_new[0] = 0, arr_new[1] = 4104 len = 2, arr_new[0] = 0
Process returned 0 (0x0) execution time : 2.721 s Press any key to continue.
Please explain me this, what's the difference b/w these printf statements and why their values are getting changed!