More CPtrArray sorting problems!

Ah hello.

A follow up to a previous question about sorting CPtrArrays.  Consider this code:

class CMyClass
      CMyClass ( DWORD d ) : m_dw ( d ) {}
      ~CMyClass() {}
      DWORD m_dw;
      CString s;

typedef int (__cdecl *GENERICCOMPAREFN)(const void * elem1, const void * elem2);
typedef int (__cdecl *STRINGCOMPAREFN)(const CMyClass * elem1, const CMyClass * elem2);

class CMyArray : public CPtrArray
      void Sort(GENERICCOMPAREFN pfnCompare = Compare)
            qsort ( GetData(), GetSize(), sizeof ( CMyClass ), ( GENERICCOMPAREFN ) pfnCompare );

      static int __cdecl Compare(const void * pMyClass1, const void * pMyClass2 )
            if ( !pMyClass1 || !pMyClass2 ) return 0;
            CMyClass* pActualMyClass1 = *(CMyClass**)pMyClass1;
            CMyClass* pActualMyClass2 = *(CMyClass**)pMyClass2;

            return pActualMyClass1 ->m_dw < pActualMyClass2 ->m_dw;

int main()
      CMyArray m_array;

      m_array.Add ( ( void*) new CMyClass ( 1 ) );
      m_array.Add ( ( void*) new CMyClass ( 3 ) );
      m_array.Add ( ( void*) new CMyClass ( 2 ) );


            return 0;

I am finding that whenever I have a CString member in the class object contained in my array, the code generates an access violation in the Compare() functoin.  More specifically, the first time the function is called by qsort(), I get my two pointers pActualMyClass1 and pActualMyClass2 both valid.  The second time however, pMyClass1 is always 0xcdcdcdcd.  So the attempt to access m_dw fails.

If I remove the CString member, this does not happen.

Can someone please tell me What is going on here, and how to get around it?  I need my CString member.

LVL 19
Who is Participating?
ZoppoConnect With a Mentor Commented:
Hi mrwad99,

I guess this line is wrong:

>             qsort ( GetData(), GetSize(), sizeof ( CMyClass ), ( GENERICCOMPAREFN ) pfnCompare );

instead of 'sizeof ( CMyClass )' you should pass 'sizeof ( CMyClass* )' since you compare pointers to CMyClass, not instances of CMyClass.

Hope that helps,

mrwad99Author Commented:
Thank you ZOPPO :o)
You're welcome ...
Zoppo is right. The previous case(without CString) worked only because
sizeof(DWORD) == sizeof(void*)
mrwad99Author Commented:
Ah, I see!  Thanks for the follow up alb66.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.