0

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!

Dr. Essen
  • 603
  • 2
  • 9
  • 25
  • 2
    `return arr;` - thus is born a dangling pointer to the caller of `arr_fun`. Your code invokes *undefined behavior*. `arr[]` ceases to exist as soon as the function returns. [**Read this**](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794). – WhozCraig Apr 09 '16 at 03:28
  • ok, but how come 1st printf showing right result? – Dr. Essen Apr 09 '16 at 03:43
  • 2
    Seriously. read the link I provided. Thus is the nature of undefined behavior. That it "seemed" to work just meant you were (un)lucky. It would have been better had you realized right off the top that something was wrong, but that seemingly correct output lulled you into believing otherwise. – WhozCraig Apr 09 '16 at 03:44
  • yeah, read that, and understood. The correct output of 1st printf statement was confusing me. It doesn't happen generally but I was lucky to get that correct but made to think upon it. Thanks. – Dr. Essen Apr 09 '16 at 06:27

0 Answers0