463 views
1 votes
1 votes
#include<stdio.h>
char *convert(int n)
{
    char s[10] = "";
    int i = 0;
    int r = 0;
    char *pp = s;
    while (n>0)
    {
        r = n % 10;
        s[i++] = r + '0';
        n = n / 10;
    }
    //printf("%s\n", pp);
    return pp;    
}

int main()
{
    int input = 123;
    char *p;
    p = convert(input);
    printf("%s\n", p);
    return 0;
}

Question: If I uncomment the printf() statement in convert() then only printf() in main() executes correctly.

Please explain.

2 Answers

1 votes
1 votes

char s[10] is local to function convert. When the control return back to the main function the activation record of convert function is deleted from the stack. So all its local variable should be deleted too. But it may happen that value of these variable is present as garbage value. And you are passing the address of the s[10] to main function, where the value at that address may or may not be present.

But when you print it in your convert function, every thing works fine.

Good Reads. 

http://www.geeksforgeeks.org/storage-for-strings-in-c/
https://gateoverflow.in/132985/const-pointer

0 votes
0 votes
#include<stdio.h>
void convert(int n)
{
    char s[10] = "";
    int i = 0;
    int r = 0;
    char *pp = s;
    while (n>0)
    {
        r = n % 10;
        s[i++] = r + '0';
        n = n / 10;
    }
printf("%s\n", pp);
   
}

int main()
{
    int input = 123;
     
convert(input);
    
}

 

this modified program will work fine

your program dint work because s[10] declared was declared locally to the function convert

once the function is executed and it comes back to main, the memoery for s[10] is destroyed

Related questions

0 votes
0 votes
0 answers
1
gmrishikumar asked Jan 2, 2019
831 views
#include<stdio.h>int main ( ){ int demo ( ); // What is this and what does it do? demo ( ); (*demo) ( );}int demo ( ){ printf("Morning");}
0 votes
0 votes
1 answer
3
Chhotu asked Nov 20, 2017
520 views
Hi,Why multiple dereferencing is not creating problem in the following program ?https://ideone.com/3Li06v (Check line 1,2 & 3. all are giving same O/P)