On Mon, Feb 22, 2010 at 5:54 AM,  <[email protected]> wrote:
> i'm confused. What's wrong with your suggestion? Why would you need to 
> allocate 'temp' if you're swapping the value (a number) at the location? 'A' 
> and 'B' already exist somewhere.

A and B (are copies of pointers that) point to something that has a size.

Temp is just a pointer that doesn't point anywhere.

The statement

Temp = A;

places whatever the _copy_ of pointer A in Temp, not the original
pointer. So calling the function with (e.g.):

int x, y;
Swap(&x, &y);

Won't actually swap anything - x will remain x and y will remain y.

The alternative John mentions whereby the statement becomes

*Temp = *A;

Is potentially worse, because it then copies whatever A points to into
whatever Temp points to, and the code, currently, doesn't tell Temp
where to point to. That ignores the facts that
1) there is no 'Void' type (it has a small v)
2) the assignment has no meaning, because 'void' has no size - i.e. a
void pointer points to an area of memory of indeterminate size. Even
MSVC refuses to compile such statements.

> Quoting John <[email protected]>:
>
>> --- In [email protected], Benjamin Scott
>> <benjamin_cail_sc...@...> wrote:
>>>
>>> You can always use the following.
>>> Â
>>> Void Swap(Void *A, void *B)
>>> {
>>>   Void *Temp
>>>
>>>  Temp = A
>>>  A = B
>>>  B = temp
>>> };
>>
>> Did you mean something like:
>>
>>   *temp = *A
>>   *A = *B
>>   *B = *temp
>>
>> I hope not, because apart from not allocating memory for *temp, it is
>> never going to work because you cannot dereference a void pointer.
>>
>> Please try compiling your code before posting.

-- 
PJH

http://shabbleland.myminicity.com/env
http://www.chavgangs.com/register.php?referer=9375

Reply via email to