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

Time:04-20

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;
}

CodePudding user response:

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) 
{
    fprintf(stderr, "bad input\n");
    exit(1);
}

In the real code the user can consider retrying getting the input as long as it is invalid.

CodePudding user response:

input changed to use the pointer correctly (&*a).

Removed the pointers to revint as it is not helping and your code had an point error there (b = c; modifies pointer not value).

#include <stdio.h>
#include <string.h>

void 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);
    b = revint(a, b);
    output(b);
    
    return 0;
}
  • Related