Syntax errors in C

Asked

Viewed 113 times

1

I’m doing this exercise in C, but I’ve locked into this part of passing parameters with pointer.

Basically the program below sums up the share 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 racking my brain trying to understand why...

IMPORTANT DETAIL!

As the exercise says, I cannot 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;
}
  • 1

    instead of printf("%d\n", b.imaginario);, shouldn’t be printf("%d\n", a.imaginario);?

1 answer

2


Thus?

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Therefore it seems to be typo, 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 probably would have made you return Complexo and wouldn’t use a pointer.

  • Our.... was breaking my head for a silly typo haha thank you very much Maniero!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.