作者softwind (software everywhere)
看板C_and_CPP
标题Re: [问题] Define complex multiply
时间Tue Nov 10 01:52:14 2009
※ 引述《dendrobium (石斛兰)》之铭言:
: 遇到的问题: (题意请描述清楚)
: 大家好,我想问一题考古题
: 题目是 中正资工95年 程式设计 第17题 题目为
: Define a C structure type Complex that represents complex numbers and a C
: function multiply that performs the multiplication of complex numbers. The
: prototype of the multiply is as follows:
: Complex *multiply(Complex*, Complex*)
: 开发平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux)
: 纯C
: 有问题的地方: (请善用置底文标色功能)
: 我的在於题目的prototype已经定好了
: 所以multiply必须回传一个Complex*
: 可是回传一个malloc出来的位置又是不好的习惯
: 回传static 的位置又会有重复call这个function的问题
: ( 像是 multiply(multiply(A,B),C) 这种 )
: 想请问一下有没有好的写法可以回传一个Complex空间又没有以上的问题
: 补充说明:
: 我的code
: typedef struct complex{
: int real,imag;
: }Complex;
: Complex *multiply( Complex *A, Complex *B)
: {
: Complex *C = ??? //<= 问题点
: C->Real = ....
: C->Imag = ....
: return C;
: }
: 抱歉我的pcmanx对於复制有控制码东西会怪怪的
: 所以就不上色了
Complex* multiply( Complex *pl, Complex *pr){
static Complex res;
Complex temp;
temp.real = (pl->real)*(pr->real)-(pl->imag)*(pr->imag);
temp.imag = (pl->real)*(pr->imag)+(pl->imag)*(pr->real);
memcpy( &res,&temp,sizeof(res) );
return &res;
}
这样可以吗?
--------------------------------------------------------
其实这个问题满好玩的 可能要用 linked list
每次传进来的两个parameters 都检查是不是在linked list里面
如果有出现了 那就再 alloc再接上去
一直到 multiply 结束
client 可以call end_of_FxxK_multiply() 来free list
不过应该有神人 可以用 递回+stack 方式解吧?
(LL 下面有人推文了 我拿上来用 thx~ )
--
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.166.115.74
1F:→ softwind:用 local stack variable 充当 额外的空间... 11/10 01:53
2F:推 VictorTom:函数被呼叫两次分别存回两个指标变数时就....XD 11/10 01:54
3F:→ softwind:也对 这样只能解 m(m(A,B),C) 这一种 11/10 01:58
4F:推 tingyushyu:typedef struct complex{ 11/10 02:02
5F:→ tingyushyu: int real,imag; 11/10 02:02
6F:→ tingyushyu: struct complex *myself; 11/10 02:02
7F:→ tingyushyu:} 11/10 02:02
8F:→ tingyushyu:Complex; 11/10 02:03
※ 编辑: softwind 来自: 118.166.115.74 (11/10 02:08)
9F:→ tingyushyu:这样free(A.myself);就可以free到A了 11/10 02:03
10F:→ tingyushyu:myself指向这个struct的位址 11/10 02:04
11F:→ tingyushyu:囧..free(A->myself); 抱歉打错 11/10 02:05