So I was practicing some coding about how functions work and I ran into a problem:
The code is meant to reverse a number. The algorithm works perfectly well so I don’t have any problem with that. But I want to use functions in my code so I edited it like below and somehow it doesn’t work anymore(there was no error, but when I run the code, after I entered in the first scanf, the code stopped and stays like that, no response). Can someone help me with this pls (This question may sound a little stupid but I’m just trying to be better at it :v)
Code:
#include <stdio.h>
#include <string.h>
int input(int *a) {
scanf("%d", &*a);
}
int revint(int *a, int *b)
{
int c;
while(a != 0)
{
c = *a % 10;
*b *= 10;
b += c;
*a /= 10;
}
return *b;
}
int output(int b) {
printf("%d", b);
}
int main()
{
int a;
int b = 0;
input(&a);
revint(&a, &b);
output(b);
return 0;
}
>Solution :
There are several issues in your code:
input()andoutput()do not have areturnstatement and should be declared to returnvoidin your code.- It makes more sense for
input()to return the value rather then fill a pointer parameter. Therefore in my versioninput()does return a properintvalue. - Several occurrences of
a,binrevint()should be*a,*b(sinceaandbare pointers and we need to de-reference it first).
See the code below:
int input(void) {
int a;
scanf("%d", &a);
return a;
}
int revint(int *a, int *b)
{
int c;
*b = 0;
while (*a != 0)
{
c = *a % 10;
*b = *b * 10 + c;
*a /= 10;
}
return *b;
}
void output(int b) {
printf("%d", b);
}
int main(void)
{
int a;
int b = 0;
a = input();
revint(&a, &b); // passing the addresses
output(b);
return 0;
}
NOTE: For simplicity the input() function doesn’t validate that scanf() actually succeeded. In should better be done in the real code in which the user is handling.
Better scanf():
if (scanf("%d", &a) != 1)
{
perror("bad input");
exit(1);
}
In the real code the user can consider retrying getting the input as long as it is invalid.