In this example, i will demostrate how to copy CPtrList, from source to destination, with just a simple calling function. If you are new to CPtrList, MSDN is a great source for you to start your journey. Also, you can refer to my previous post on Using CPtrList to store data into memory as a reference.
  1. Let’s create a CPtrList copy function now.
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    void CopyLinkList(CPtrList *pDestList, CPtrList *pSrcList, int size)
    {
      // Always check the validity of pointer list source
      if (!pSrcList)
        return;

      // Copy from source to destination
      for (POSITION pos = pSrcList->GetHeadPosition(); pos != NULL;)
      {
        LPVOID pNode  = pSrcList->GetNext(pos);
        if(IsBadReadPtr(pNode, 1)) break;

        char * pChar = (char*)malloc(size);
        memcpy(pChar, pNode, size);
        pDestList->AddTail(pChar);
      }
    }
  3. We now create a new CPtrList variable and call the function as following.
  4. 1
    2
    3
    4
    5
    6
    // CPtrList variable - this will hold the copy data
    CPtrList pNewList;

    // We call the following function to initialize the
    // copy process
    CopyLinkList(&pNewList, &pList, sizeof(ST_NAME));
That’s all we need to do in order to copy all data from the source CPtrList to newly declare destination CPtrList.