0
void swap (int *a, int *b)
{
    int tmp = *a;                 
    *a = *b;
    *b = tmp;
}

I want to know if int tmp = *a, "*a" means an int value, then *a = *b, both *a and *b become pointers, then *b in the last line becomes the value again.

Is this correct?

1

Remember that parameters in function call should pass the address of variables like swap(&p, &q);

Ideone

int tmp = *a;

The value stored at the memory block to which a was pointing, is being stored in tmp

*a = *b;

The pointer a is made to point to where the pointer b was pointing initially. Till now, *a holds the value of pointed by b, *b retains its own value, and tmp holds the value of *a at the beginning of the function.

*b = tmp;

b is made to point to a location where tmp stores its value.

Finally, values swapped.

| improve this answer | |
  • Thank you very much sinister. So this is for integer type....what to do with 2-dimensional array? is it board[i][j] the pointer of board[i][j] or board[inti][int*j} the correct syntax? – Hang Man Dec 28 '14 at 7:58
  • Sorry, can't understand what you are asking! Can you make it a bit clear. – sinister Dec 28 '14 at 13:04
  • thanks, I have just sorted out the problem. – Hang Man Dec 29 '14 at 2:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .