krn
krn

Reputation: 6815

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(&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.

Upvotes: 0

Views: 133

Answers (4)

Charles Keepax
Charles Keepax

Reputation: 2402

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.

Upvotes: 1

wong2
wong2

Reputation: 35720

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.

Upvotes: 0

Diego Sevilla
Diego Sevilla

Reputation: 29011

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.

Upvotes: 2

sharptooth
sharptooth

Reputation: 170469

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

Upvotes: 2

Related Questions