Home > database >  why is my pointer passing function giving me a wrong output?
why is my pointer passing function giving me a wrong output?

Time:10-29

the following is given

#include  <stdio.h>    
void func2 (int num, int *result);   
int main()    
{    
   int num, result;    

   printf("Enter a number: \n"); 
   scanf("%d", &num);
   func2(num, &result);    
   printf("func2(): %d\n", result);    
   return 0;    
}

void func2(int num, int *result)     
{    
//key in code    
}

in the void func2 i wrote

int i=0;    
result=&i;      
while (num!=0)    
{    
i =((num%10)*(num%10));    
num=num/10;    
}

but the programming is not returning the value of variable i properly. what's wrong with my variable assignment?

expected output:

Enter a number:    
24 (user enter)    
func2(): 20

actual output:

Enter a number:    
24 (user enter)    
func2(): 32767

CodePudding user response:

You need to assign indirectly through result, not set result to the address of another variable.

int i=0;    
while (num!=0)    
{    
    i =((num%10)*(num%10));    
    num=num/10;    
}
*result = i;
  • Related