I have a quick question that is been bugging me.

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

I wrote this intending it to be either able to swap a structure, or just the data defined within a structure.

Will the swap function be able to do this, because.. when i tested it, it seemed to fail. but i didnt except it too.

it should atleast work for swapping the data stored within the structure though, shouldnt it? (the data is of type event, which is shown below the heap struct).


** here are the structures **

struct heap_s
{
     heap left, right;
     void* data;
};

struct event_s {
     etime       time;
     int     e_num;
     void        (*event_fn)(event,  pqueue);
     void        *details;
     };

Recommended Answers

All 2 Replies

I wrote this intending it to be either able to swap a structure, or just the data defined within a structure.

Will the swap function be able to do this, because.. when i tested it, it seemed to fail. but i didnt except it too.

It fails because all it does is swap the pointers within the swap() function itself because the pointers are passed by value, not by reference.

void swap(void** a, void** b)
{
    void* temp = *a;
     *a = *b;
      *b = temp;
}

Now the above will work ONLY if you pass a pointer to a pointer. It will also fail if you pass a pointer to some object.

int main()
{
    int a = 1;
    int b = 2;
    swap(&a, &b); // <<<<<<< wrong

    int* c = &a;
    int* d = &b;
    swap(&c, &d); // <<< OK
// when the swap returns, pointer c will point to b and pointer d will point to a.
// The value of [b]a[/b] and [b]b[/b] are still the same, only the two pointers
// were swapped

it should atleast work for swapping the data stored within the structure though, shouldnt it?

No.

oh, i see what i was doing wrong.

thanks for the quick reply.

i have added the updates and passed it the memory address now as you showed.

you can add the lovely "Solved" heading to my topic. Thankyou so much for such a quick reply.

This board has been really useful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.