Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i use function in my code and somehow it doesnt work anymore

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are several issues in your code:

  1. input() and output() do not have a return statement and should be declared to return void in your code.
  2. It makes more sense for input() to return the value rather then fill a pointer parameter. Therefore in my version input() does return a proper int value.
  3. Several occurrences of a, b in revint() should be *a,*b (since a and b are 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading