So I need to calculate the reverse of a number using pointers in a function. I get junk memory when I run it.Here is what I tried.(When I remove the p ,it works, I don't get any junk memory but than I can calculate only the remainder , I don't get why?)
I m sorry for the earlier post. I read the rules of Stack Overflow.
Here is the code:
int Invers(int x , int *Calculinvers ){
int rem = 0;
int p = 1
while(x!=0){
rem = x % 10 ;
*Calculinvers = p*10 rem;
x = x / 10;
}
return *Calculinvers;
}
int main(){
int a;
printf("Introduceti numarul caruia vreti sa-i calculati inversul : \n");
scanf("%d" , &a);
int Calcul;
Invers(a , &Calcul);
printf("Inversul numarului este : %d\n" , Calcul);
return 0;
}
CodePudding user response:
Two problems and fixes:
(1)*Calculinvers
needs to be initialized to 0, or system will give you unexpected value.
(2)Replace *Calculinvers = p*10 rem;
to *Calculinvers = *Calculinvers*10 rem;
because you did not add the previous value.
CodePudding user response:
I threw together this, it seems to work:
#include <stdio.h>
int reverse(int x)
{
out = 0;
while (x != 0)
{
const int ones = x % 10;
out *= 10;
out = ones;
x /= 10;
}
return out;
}
int main(void) {
const int num[] = { 0, 1, 10, 47, 109, 4711, 1234, 98765432 };
printf("I got:\n");
for (int i = 0; i < sizeof num / sizeof *num; i)
{
printf(" %d -> %d\n", num[i], reverse(num[i]));
}
return 0;
}
It prints:
I got:
0 -> 0
1 -> 1
10 -> 1
47 -> 74
109 -> 901
4711 -> 1174
Obviously when we're working with actual integers, trailing zeroes turn into leading zeroes which don't really exist unless we store the original number's length and pad when printing. That's why 10
turns to 1
, for instance.
This is better suited as a pure string-space operation, since then each digit exists as part of the string rather than as part of the representation of a number (which has other conventions).
Update:
If you really want to use pointers, you can of course wrap the above in a more pointery shroud:
void reverse_at(int *x)
{
const int rev = reverse(*x);
*x = rev;
}
but as stated in comments (and hopefully illustrated by my code) a more functional approach where the return value calues the result of a function is generally more easily understood, safer, and just better.