1

为什么这段代码可以完美执行Dev-CPP但无法执行Borland Turbo C

在 Turbo C 中执行时,它显示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);
}
4

1 回答 1

1

无需按值传递结构成员。可以执行以下操作:

#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;
}
于 2012-03-26T20:14:37.863 回答