Swap of pointers in structure

I'm stuck with this. I have already defined structure Item and AllItem is following structure:

struct AllItem {
int ID;
Item *ItemPt;
};

I'm trying to write a Swap function, which takes two parameters of type AllItem and swaps the ItemPt fields of the two parameters. I only need to swap pointers.

I'm quite lost in the struct pointer relation...
I assume, I can do something like this, but I'm not sure about the correctness of the code...

1
2
3
4
5
6
void switchIt(DataItem *a, DataItem *b){
	DataItem *temp;
	temp.itemPtr = *a.itemPtr;
	*a.itemPtr = *b.itemPtr;
	*b.itemPtr = temp.itemPtr;
}

Line 2 should not be a pointer.
Also better to use the member of operator.

1
2
3
4
5
6
void switchIt (DataItem *a, DataItem *b)
{  DataItem temp;
    temp.itemPtr = a->itemPtr;
    a->itemPtr = b->itemPtr;
    b->itemPtr = temp.itemPtr;
}
Thank you for a quick answer.

To make it clear to me, because it's very hard for me to imagine the relations between those pointers...

I should call this function with
SwitchIt(&first, &second);
which provides the addresses. Then they are stored in pointers *a and *b, which I can now switch, right?

What I donĀ“t understand is, why it works with pointers inside the function if I want to switch just the addresses(values of pointers)? Doesn't it swich the actual values it's pointing at?

What would change if I passed just
SwitchIt(first, second);
or simply swaped the parameters like this
1
2
3
    temp.itemPtr = a.itemPtr;
    a.itemPtr = b.itemPtr;
    b.itemPtr = temp.itemPtr;


Thank you
Then they are stored in pointers *a and *b, which I can now switch, right?

You're not switching a and b, but members (*ItemPt) of a and b.

Doesn't it swich the actual values it's pointing at?

An *ItemPtr is a storage location which contains the address of an Item.
What you did was to swap the two storage locations containing the addresses of the respective items. You didn't touch the item objects.

What would change if I passed just
SwitchIt(first, second);

That wouldn't compile, because first and second are not pointers.
However, you could also pass first and second by reference rather than by pointers.
1
2
3
4
5
6
void switchIt (DataItem & a, DataItem & b)
{  DataItem temp;
    temp.itemPtr = a.itemPtr;
    a.itemPtr = b.itemPtr;
    b.itemPtr = temp.itemPtr;
}

Tank you! I think I got it now...
Last edited on
Topic archived. No new replies allowed.