Home > Enterprise >  Error in the program to find absolute difference in C
Error in the program to find absolute difference in C

Time:09-21

I want to calculate the sum and absolute difference of the two variable in this program.

#include <stdio.h>
#include <stdlib.h>

void update(int *a,int *b) {
    // Complete this function    
    *a= *a *b;
    *b= abs(a-b);
    
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;
    
    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%d\n%d", a, b);

    return 0;
}

But for some inputs this doesn't produce correct outputs for the absolute difference.eg.(4,5) produce correct outputs; (2,6) doesn't. I am unable to figure out the mistake. What is the reason?

CodePudding user response:

As pointed out in other answer subtracting two pointers is UB.

To answer other part of problem, Try to understand what is happening to the pointer values at each point of arithmetic operation,

void update(int *a,int *b) {
    // Complete this function    
    *a= *a *b; //<< here *a has sum of *a and *b

    *b= abs(*a-*b); 
    //here *a itself is *a  *b 
    //so entire operation is abs(*a   *b -*b) and hence *b will have value of abs(*a)   
}

Try to have local variables to keep intermediate values and assign it at the end,

void update(int *a,int *b) {
    int sum = *a   *b;        
    int diff = abs (*a -*b);

    *a= sum;
    *b= diff;        
}

CodePudding user response:

*b= abs(a-b);

You are subtracting the pointers, which is undefined behavior because they don't point into the same array. You want to be subtracting the numbers they point to. Make this

*b= abs(*a-*b);
  •  Tags:  
  • c
  • Related