C:将指针切换为整数

发布于 2024-11-07 22:25:26 字数 293 浏览 0 评论 0原文

我想编写一个方法,它接受两个指向整数的指针并更改它们指向的值。例如:

int main() {
    int a = 3;
    int b = 1;
    change(&a, &b);
    return 0;
}

void change(int *a, int *b) {
    int t = a;
    *a = *b;
    *b = *t;
}

我在理解如何保存 a 的副本并稍后从 b 指向它时遇到问题。

I want to write a method which takes two pointers to ints and changes the values they point to. Something like:

int main() {
    int a = 3;
    int b = 1;
    change(&a, &b);
    return 0;
}

void change(int *a, int *b) {
    int t = a;
    *a = *b;
    *b = *t;
}

I have a problem understanding how to save a copy of a and point to it from b later.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

晒暮凉 2024-11-14 22:25:26

你这样做:

int temp = *a; // remember actual value "a" points to
*a = *b; // copy value "b" points to onto value "a" points to (will overwrite that value, but we have a copy in "temp")
*b = temp; // now copy value "a" originally pointed to onto value "b" points to

You do it like this:

int temp = *a; // remember actual value "a" points to
*a = *b; // copy value "b" points to onto value "a" points to (will overwrite that value, but we have a copy in "temp")
*b = temp; // now copy value "a" originally pointed to onto value "b" points to
请别遗忘我 2024-11-14 22:25:26

change 的代码应该是:

void change(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

请注意,要访问该值,您始终必须使用 *X,因此首先 t 保存指向的值到a,依此类推。

The code for change should be:

void change(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

Note that for accessing the value, you always have to use *X, so first t holds the value pointed to by a, and so on.

驱逐舰岛风号 2024-11-14 22:25:26

* 取消引用指针,这就像返回所指向的变量。因此,将值存储到取消引用的指针中将导致该值存储到所指向的内存中。因此,只需取消引用两个指针并专门处理数字,无需更改指针本身。

void change(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

事实上,因为您对函数的参数使用了按值调用,所以交换“change”内指针中的内存地址对 main 内的变量根本没有影响。

The * dereferences a pointer, this is like returning the variable that is pointed to. So storing a value into the dereferenced pointer will cause that value to be stored into the memory that is pointed to. So simply dereference both pointers and deal exclusively with the numbers, there is no need to go changing the pointers themselves.

void change(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

Indeed because you have used call-by-value for the arguments to the function swapping the memory addresses in the pointers within "change" will have no effect on the variables inside main at all.

扬花落满肩 2024-11-14 22:25:26

你有

void change(int *a, int *b) {
    int t = a;
    *a = *b;
    *b = *t;
}

没有注意到a的类型是int *t的类型是int,所以你不能只将 a 分配给 t

In

void change(int *a, int *b) {
    int t = a;
    *a = *b;
    *b = *t;
}

haven't you notice that a's type is int * while t's type is int, so you can't just assign a to t.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文