double-ptr usage #2b — swap 2 pointers

(Note this is a special case of “special reseating” —

Q1: write a utility function to swap 2 pointer’s content.
%%A: swap(int** a, int** b) {….}
Obviously, the 2 pointer Variables must be declared to be compatible — to be elaborated [1], such as
int* a1, b1; …. swap(&a1, &b1);

To really understand why we need double pointers, consider

Q2: function to swap 2 nonref variables. In other words, after i call swap(..), x should have the value of y. If y used to be -17.2, x now has that value. Note this number isn’t an address.

In this case, you need to pass the address of x like &x….

To understand this Q2, it’s actually important to be be thoroughly familiar with

Q3: what does swap(char i, char j) do?
%%A: something other than swapping. I doubt it does anything meaningful at all. It receives two 8-bit chars by value. It doesn’t know where the original variables are physically, so it can’t put new values into those original variables, so it can’t swap them.

Any swap must use some form of pass-by-reference.

Q1b: function to swap 2 arrays. After the swap, array1 is still a pointer but it points to the physical location of array2
%%A: same signature as Q1.

[1] void ** is probably a feasible idea but may require casting. Usually the 2 arguments a1 and b1 should have the same declaration. If a1 is Animal* and b1 is Dog* (Note the single asterisks), then such a polymorphic swap is no longer straight-forward and fool-proof.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s