Re: [問題] Define complex multiply

看板C_and_CPP作者 (software everywhere)時間16年前 (2009/11/10 01:52), 編輯推噓2(209)
留言11則, 3人參與, 最新討論串2/2 (看更多)
※ 引述《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

11/10 01:53, , 1F
用 local stack variable 充當 額外的空間...
11/10 01:53, 1F

11/10 01:54, , 2F
函數被呼叫兩次分別存回兩個指標變數時就....XD
11/10 01:54, 2F

11/10 01:58, , 3F
也對 這樣只能解 m(m(A,B),C) 這一種
11/10 01:58, 3F

11/10 02:02, , 4F
typedef struct complex{
11/10 02:02, 4F

11/10 02:02, , 5F
int real,imag;
11/10 02:02, 5F

11/10 02:02, , 6F
struct complex *myself;
11/10 02:02, 6F

11/10 02:02, , 7F
}
11/10 02:02, 7F

11/10 02:03, , 8F
Complex;
11/10 02:03, 8F
※ 編輯: softwind 來自: 118.166.115.74 (11/10 02:08)

11/10 02:03, , 9F
這樣free(A.myself);就可以free到A了
11/10 02:03, 9F

11/10 02:04, , 10F
myself指向這個struct的位址
11/10 02:04, 10F

11/10 02:05, , 11F
囧..free(A->myself); 抱歉打錯
11/10 02:05, 11F
文章代碼(AID): #1A-5RHNM (C_and_CPP)
文章代碼(AID): #1A-5RHNM (C_and_CPP)