【发布时间】:2010-09-20 08:19:23
【问题描述】:
这听起来像是一个愚蠢的问题,但我还在学习 C,所以请多多包涵。 :)
我正在编写 K&R(结构)的第 6 章,到目前为止,这本书已经取得了巨大的成功。我决定大量使用结构体,因此在本章的开头用 point 和 rect 示例做了很多工作。我想尝试的一件事是通过指针更改 canonrect 函数(第 2 版,第 131 页)工作,从而返回 void。
我有这个工作,但遇到了一个小问题,我希望你们能帮助我。我希望canonRect 创建一个临时矩形对象,执行它的更改,然后将它传递给临时矩形的指针重新分配,从而简化代码。
但是,如果我这样做,矩形不会改变。相反,我发现自己手动重新填充了我传入的 rect 的字段,这确实有效。
代码如下:
#include <stdio.h>
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
struct point {
int x;
int y;
};
struct rect {
struct point lowerLeft;
struct point upperRight;
};
// canonicalize coordinates of rectangle
void canonRect(struct rect *r);
int main(void) {
struct point p1, p2;
struct rect r;
p1.x = 10;
p1.y = 10;
p2.x = 20;
p2.y = 40;
r.lowerLeft = p2; // note that I'm inverting my points intentionally
r.upperRight = p1;
printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n",
r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y);
// can't pass a pointer, only a reference.
// (Passing pointers results in illegal indirection compile time errors)
canonRect(&r);
printf("Rectangle, lower left: %d, %d; upper right: %d %d\n\n",
r.lowerLeft.x, r.lowerLeft.y, r.upperRight.x, r.upperRight.y);
}
void canonRect(struct rect *r) {
struct rect temp;
temp.lowerLeft.x = min(r->lowerLeft.x, r->upperRight.x);
temp.lowerLeft.y = min(r->lowerLeft.y, r->upperRight.y);
temp.upperRight.x = max(r->lowerLeft.x, r->upperRight.x);
temp.upperRight.y = max(r->lowerLeft.y, r->upperRight.y);
r = &temp; // doesn't work; my passed-in rect remains the same
// I wind up doing the following instead, to reassign all
// the members of my passed-in rect
//r->lowerLeft = temp.lowerLeft;
//r->upperRight = temp.upperRight;
}
以下是问题:
- 为什么
r = &temp;不起作用? (我认为这是因为我传入的是引用而不是指针;我认为引用不可修改但指针可以修改是否正确?) - 如果我尝试传递指向
canonRect的指针,为什么会收到非法间接编译时错误? (即,如果我在main()中有canonRect(*r);。)
我怀疑我已经知道#1 的答案,但#2 让我感到困惑——我认为传递指针是合法的。
无论如何...请原谅C新手。
【问题讨论】:
标签: c pointers struct reference