Sourav
Sourav

Reputation: 17530

Complex number addition using structure

Why does this code execute perfectly on Dev-CPP but fails to execute on Borland Turbo C?

When executing in Turbo C it shows Input real part: Stack Overflow !

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

struct complex
{
 int real;
 int img;
};

typedef struct complex com;
com read(com);
com add(com,com);
void show(com);

void main()
{
 com c1,c2,c3;
 clrscr();
 c1=read(c1);
 c2=read(c2);
 c3=add(c1,c2);
 show(c3);
 getch();
}

com read(com c)
{
 printf("Input real part: ");
 scanf("%d",&c.real);
 printf("Input imaginary part: ");
 scanf("%d",&c.img);
 return (c);
}

void show(com c)
{
 printf("%d+%di",c.real,c.img);
}

com add(com c1,com c2)
{
 com c3;
 c3.img=c1.img+c2.img;
 c3.real=c1.real+c2.real;
 return (c3);
}

Upvotes: 1

Views: 1997

Answers (1)

user138645
user138645

Reputation: 782

No need to pass around struct members by value. Can do the following:

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

struct complex
{
  int real;
  int img;
};

typedef struct complex com;
void read(com *);
void add(com,com, com *);
void show(com);

int main()
{
  com c1,c2,c3;
  read(&c1);
  read(&c2);
  add(c1,c2, &c3);
  show(c3);
  return 0;
}

void read(com *c)
{
  printf("Input real part: ");
  scanf("%d",&c->real);
  printf("Input imaginary part: ");
  scanf("%d",&c->img);
}

void show(com c)
{
  printf("%d+%di",c.real,c.img);
}

void add(com c1,com c2, com *c3)
{
  c3->img=c1.img+c2.img;
  c3->real=c1.real+c2.real;
}

Upvotes: 1

Related Questions