作者pponywong (pony)
看板C_and_CPP
标题Re: [问题] structure swap
时间Mon Feb 23 20:38:32 2009
※ 引述《tata111 (aa)》之铭言:
: 我发现在swap的function中有对调
: 可是在主程式中却没有
: 是哪里写错了吗?
: 程式码: http://rafb.net/p/eH9UrW78.html
: 执行结果
: i=0, width=10.000000, length=10.000000,area=100.000000
: i=1, width=2.000000, length=3.000000,area=6.000000
: i=2, width=5.000000, length=7.000000,area=35.000000
: Before swap: 0022FF40 0022FF4C
: swap function: before 0022FF40 0022FF4C
: swap function: after 0022FF4C 0022FF40
: After swap: 0022FF40 0022FF4C
: i=0, width=10.000000, length=10.000000,area=100.000000
: i=1, width=2.000000, length=3.000000,area=6.000000
: i=2, width=5.000000, length=7.000000,area=35.000000
结论是你 swap 写错了, 给你个对的
void swap(struct rectangle *data1, struct rectangle *data2)
{
struct rectangle temp;
memcpy(&temp, data1, sizeof(temp));
memcpy(data1, data2, sizeof(temp));
memcpy(data2, &temp, sizeof(temp));
}
顺便问问自己为什麽你那样写会错吧 ....
给你个提示, 参数里的指标改值会影响到 caller 吗 ?
void test(int a, int b); // test 里面改 a, b 会影响到 caller 吗 ?
void test(int* a, int* b); // test 改 a, b 会影响到 caller 吗 ?
void test(int* a, int* b); // test 改 *a, *b 会影响到 caller 吗 ?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.114.207.94