本文介绍了C指针-指向相同的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
#include <stdlib.h>
void foo(int *a, int *b);
void foo(int *a, int *b) {
*a = 5;
*b = 6;
a = b;
}
int main(void) {
int a, b;
foo(&a, &b);
printf("%d, %d", a, b);
return 0;
}
为什么a = b(foo)不起作用? printf输出"5,6"谢谢.
Why a = b (foo) doesn't work? printf outputs "5, 6"Thank you.
推荐答案
它确实有效;它只是没有按照您的想法做.
It does work; it just doesn't do what you think it does.
在foo()
中,a = b
将指针a
更改为指向b
所指向的内容.它对功能以外的任何内容均无影响;它只会更改指针.
In foo()
, a = b
changes the pointer a
to point to whatever b
points to. It has no effect on anything outside of the function; it only changes the pointers.
如果您想将a
指向的int的值更改为与b
指向的int的值相同,则需要使用*a = *b
,类似于您执行函数中已经有分配.
If you want to change the value of the int pointed to by a
to be the same as the value of the int pointed to by b
, you need to use *a = *b
, similar to how you do the assignments in the function already.
这篇关于C指针-指向相同的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!