1

My function is unable to compare 2 pointer values. The main function has two variables a and b. Swap function swaps the value of a and b. In my max function I cant find the bigger number between c and a. It is not working properly as a always become the bigger number.

//swap two varibales
int swap(int *a, int *b )
{
    int temp = *a;

    *a= *b;
    *b = temp;
        printf("After swap: A = %d and B = %d", *a, *b);
}

This function takes the input of c and adds all three numbers.

int additon(int *a, int *b, int *c, int *total)
{

    printf(" \nInput Numbers you want: ");
    scanf("%d", c);

    *total = *a + *b  + *c;
    printf("\n\nTotal value of numbers %d, %d, %d  are = %d",*a,*b, *c, *total );

}

Function which compares between a and c [problem] :

int max(int *a, int *b, int *c,int *maxNum)
{

    if( a > c)
    {
        printf("\n\n A = %d is bigger than C = %d", *a,*c);
    }

    else if( a < c)
    {
        printf("\n\n A = %d is smaller than C = %d",*a,*c);
    }
}

Main function:

int main(int *total, int *maxNum)
{
    int *a = 10;
    int *b = 20;
    int *c;

    printf("Before swap: A = %d and B = %d\n", a,b);

    swap(&a, &b);

    additon(&a, &b, &c, &total);
    max(&a, &b, &c, &maxNum);

    return 0;
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 1
    `if( a > c)` -> `if(*a > *c)` etc. Or better still, just pass in `int`s instead of pointers. There is no reason why at least the first three args to `max` need to be pointers. – kaylum Jun 16 '21 at 04:02
  • 1
    OT: `int main(int *total, int *maxNum)` that is an invalid definition of the `main` function. [What are the valid signatures for C's main() function?](https://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function) – kaylum Jun 16 '21 at 04:05
  • Most of those parameters could be `int` rather than `int*`. A function that doesn't return a value should be declared as `void`. Your `additon` and `max` functions could return a value rather than storing it via a pointer argument. Your `swap` function does need to use pointers, though. – Keith Thompson Jun 16 '21 at 05:47

1 Answers1

1

You need to dereference the pointers. Like this:

 if( *a > *c)
    {
        printf("\n\n A = %d is bigger than C = %d", *a,*c);
    }

 else if( *a < *c)
    {
        printf("\n\n A = %d is smaller than C = %d",*a,*c);
    }

In the previous version your were comparing the addresses the pointers held.

ADBeveridge
  • 650
  • 3
  • 15