C++: Can't work with simple pointers?
I apologize as this is so simple, I was working with my own XOR swap method and wanted for the he开发者_如何转开发ck of it compare the speed difference between reference and pointer use (do not spoil it for me!)
My XOR ptr function is as follows:
void xorSwapPtr (int *x, int *y) {
if (x != y && x && y) {
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
I copied this to a xorSwapRef function which just uses refs (int &x, etc.) anywho:
I use it like this but I get the error error: invalid conversion from ‘int’ to ‘int*’
int i,x,y = 0;
for(i=0;i<=200000;i++) {
x = rand();
y = rand();
xorSwapPtr(x, y); //error here of course
}
How would I use the pointer function with ints, like the ref one? I just wonder because the example xor function I found in a book uses pointers, hence my wanting to test.
x
and y
are int
s; xorSwapPtr
takes two int*
s, so you need to pass the addresses of x
and y
, not x
and y
themselves:
xorSwapPtr(&x, &y);
The syntax can be confusing...
When you want to pass a pointer to something, you usually take the address of it, like &something
. However, when declaring a function signature, and you want to define one of the parameters to be a reference to a Type called somethingElse, then you would use Type &somethingElse
. Both of these use the & token, but they mean 2 different things (different semantics for the token &, just like * could mean multiply, define a pointer to, or dereference a pointer, each depending upon its grammatical place in the code).
void foo(int *x, int *y); // declare a function that takes two pointers to int
void bar(int &x, int &y); // declare a function that takes two references to int
now let's use them...
int i, j;
foo(&i, &j); // pass in the address of i and the address of j
bar(i, j); // pass in a reference to i and a reference to j
// can't tell by the call that it is a reference - could be "by value"
// so you gotta look at the function signature
This bit
xorSwapPtr(x, y);
Needs to be
xorSwapPtr(&x, &y);
Hope this helps
精彩评论