0
I'm pretty sure I covered this in C, but there was something about the way the ints were stored that this function wouldn't update the variables properly... Can anyone confirm, or expand?
3 ответов
+ 3
The swap function is a classic. I believe this is what you are talking about:
//arguments: two int variables
void swap(int &a, int &b) {
int c;
c = a;
a = b;
b = c;
}
//call: swap(var1, var2)
This function uses references to get a direct access to the variables, with the changes being persistent. A reference is close to a pointer as they both hold an address, but they aren't quite the same. You don't need to dereference a reference (with *) to manipulate the variable for example. Here is an equivalent with pointers:
//arguments: two addresses of int variables
void swap(int *a, int *b) {
int c;
c = *a;
*a = *b;
*b = c;
}
//call: swap(&var1, &var2)
Any question?
+ 2
...That's a vague description. Could you find the code bit you are talking about and post it here?
0
it was the pointers section of cs50x if I remember right, I don't have the code to hand... The example had three variables, a b and c and the program was meant to swap the data from a and b around using c as an intermedeary. I don't have the code to hand though 😥