-1

A function receives two integer pointers, int* a and int* b. Set the value of *a to their sum, and *b to their absolute difference.

There is no return value, and no return statement is needed.

I got the values for *a but I'm unable to get the code for *b.

#include <stdio.h>
void update(int *a,int *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;
}
void update(int *a,int *b) 
{
    *a+=*b;
    *b=*a-*b;
}
EsmaeelE
  • 2,331
  • 6
  • 22
  • 31
Chandana
  • 11
  • 3

3 Answers3

1

You may use a temporally variable to store value of *a and then use it:

int tmp = *a;
*a += *b;
*b = abs(tmp - *b);
CuriousPan
  • 783
  • 1
  • 8
  • 14
1

A little cleanup. Only the function needs pointers. Your main does not.

#include <stdio.h>
#include <stdlib.h>  // abs()

void sum_and_diff( int * a, int * b )
{
  int sum = *a + *b;
  int diff = abs( *a - *b );
  *a = sum;
  *b = diff;
}

int main(void)
{
  int a, b;

  printf( "a? " );  scanf( "%d", &a );
  printf( "b? " );  scanf( "%d", &b );

  sum_and_diff( &a, &b );

  printf( "sum = %d\n", a );
  printf( "absolute difference = %d\n", b );

  return 0;
}
Dúthomhas
  • 8,200
  • 2
  • 17
  • 39
  • Good answer, but I suggest always check return value of `scanf()` to ensure correct values. First initialize variables with zero to avoid wrong result in future. – EsmaeelE Jan 23 '23 at 10:52
  • 1
    For a homework this use of `scanf()` will do. For anything else, [`scanf()` is the wrong tool](https://stackoverflow.com/questions/2430303/disadvantages-of-scanf). In this case there is no advantage to overloading OP with the usual _how to get an integer_ thesis. – Dúthomhas Jan 23 '23 at 10:55
  • It's better to add some explanation about C function pass by reference emulation. https://stackoverflow.com/q/2229498/7508077 – EsmaeelE Jan 23 '23 at 10:58
0

A simple answer (the simplest?), that doesn't require temporary variables or external functions like abs(), is:

void update(int *a, int *b) 
{
    *a += *b;
    *b =  *a-*b-*b;
}

It fixes your code by also subtracting the "extra" *b you just added to *a

mmixLinus
  • 1,646
  • 2
  • 11
  • 16