C:将指针切换为整数
我想编写一个方法,它接受两个指向整数的指针并更改它们指向的值。例如:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你这样做:
You do it like this:
change
的代码应该是:请注意,要访问该值,您始终必须使用
*X
,因此首先t
保存指向的值到a
,依此类推。The code for
change
should be:Note that for accessing the value, you always have to use
*X
, so firstt
holds the value pointed to bya
, and so on.* 取消引用指针,这就像返回所指向的变量。因此,将值存储到取消引用的指针中将导致该值存储到所指向的内存中。因此,只需取消引用两个指针并专门处理数字,无需更改指针本身。
事实上,因为您对函数的参数使用了按值调用,所以交换“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.
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.
你有
没有注意到
a
的类型是int *
而t
的类型是int
,所以你不能只将a
分配给t
。In
haven't you notice that
a
's type isint *
whilet
's type isint
, so you can't just assigna
tot
.