C: switch pointers to integers
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(&开发者_如何学Camp;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.
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
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.
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.
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
.
精彩评论