Syntax errors in C [closed]

1

I'm doing this exercise in C, but I caught that part of passing pointer parameters.

Basically the program below adds the portion of real numbers and integers.

The problem is that the current results are:

a = 12 (correct!)

b = 10 (Wrong!)

The result of B is incorrect and I'm breaking my head trying to understand why ...

IMPORTANT DETAIL!

As the exercise speaks, I CAN NOT CHANGE THE MAIN

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

struct Complexo {
  int real;
  int imaginario;
};

struct Complexo insereComplexo(int r, int i){
  struct Complexo novo;
  novo.real = r;
  novo.imaginario = i;
  return novo;
}

void somaComplexo(struct Complexo *a, struct Complexo b){
  a->real += b.real;
  a->imaginario += b.imaginario;
}

int main(int argc, char *argv[]){
  struct Complexo a, b;
  a = insereComplexo(4,7);
  b = insereComplexo(8,10);
  somaComplexo(&a, b);
  printf("%d\n", a.real);
  printf("%d\n", b.imaginario);
  system("pause");
  return 0;
}
    
asked by anonymous 31.05.2018 / 18:55

1 answer

2

So?

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

struct Complexo {
  int real;
  int imaginario;
};

struct Complexo insereComplexo(int r, int i){
  struct Complexo novo;
  novo.real = r;
  novo.imaginario = i;
  return novo;
}

void somaComplexo(struct Complexo *a, struct Complexo b){
  a->real += b.real;
  a->imaginario += b.imaginario;
}

int main(int argc, char *argv[]){
  struct Complexo a, b;
  a = insereComplexo(4,7);
  b = insereComplexo(8,10);
  somaComplexo(&a, b);
  printf("%d\n", a.real);
  printf("%d\n", a.imaginario);
  system("pause");
  return 0;
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

Porting seems to be typing error, since it is accumulating the values in a , and prints the real of a , but the imaginary prints of b that is not accumulating anything.

I would probably have returned Complexo and would not use pointer.

    
31.05.2018 / 19:04