tags:

views:

80

answers:

4

I have two structs of the same type, the fields are comprised of strings. One struct is a "current/changed" state, the other is an original state.

Is there a simple way to determine if the fields have changed other than iterating through each field and comparing one-by-one?

+4  A: 

Define getters and setters to interface with your struct and maintain a "modified" flag.

Otherwise, there's no readily usable way for you to know if memory contents changed since last time you read it other than comparing data AFAIK.

Wadih M.
+1  A: 

I beleive that for Structs of the same type, you can just to a striaght compare. I.E., IF (structA = strucB) then ...

Nope, my bad. I was thinking of VB6...

Oh wait, there's another way to do it in .NET: using the .Equals method.

Public Class TestVBClass
Structure pnt
    Dim X As Single
    Dim Y As Single
    Dim Name As String
End Structure


Function CompareStructs() As Boolean
    Dim a As pnt, b As pnt

    With a
        .X = 3.3
        .Y = 1.1
        .Name = "first"
    End With
    With b
        .X = 13.3
        .Y = 11.1
        .Name = "second"
    End With
    MsgBox("Test1 = " & (a.Equals(b)), MsgBoxStyle.OkOnly)

    With b
        .X = 3.3
        .Y = 1.1
        .Name = "first"
    End With
    MsgBox("Test2 = " & (a.Equals(b)), MsgBoxStyle.OkOnly)
End Function
End Class
RBarryYoung
A: 

Are the strings char pointer of char arrays? If it's arrays, you can do a memcmp for the sizeof(struct). That's sort of a brute force still, but at least it's more efficient then dereferencing the fields one by one.

If the fields are char pointers and the strings themselves don't change (so the field points to either "string1" or "string2", but the "string1" itself will never change) the memcmp can work too. Else you'll have to make a manual compare function.

Update: I didn't see the .net tag before. I'm talking about plain C, I don't know about .net, so this might not apply.

Ron
+1  A: 

I would implement IComparable and then do a field compare.

eschneider