In this example, i will store 10 records into the memory using CPtrList.
  1. Let’s start the example by creating a Win32 console application from my VS2005 IDE.
  2. win32_console_app
  3. Make sure that we add common header files to support MFC.
  4. mfc_common_header
  5. Let’s start the coding by creating a simple struct with 2 char data type variables.
  6. 1
    2
    3
    4
    5
    6
    // Create a simple struct to example
    typedef struct
    {
      char szFName[30];
      char szLName[30];
    } ST_NAME, FAR * LP_ST_NAME;
  7. Let’s create a CPtrList variable now and store 10 records into the memory now.
  8. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // CPtrList variable
    CPtrList pList;

    // We are going to store 10 records into CPtrList
    ST_NAME stName[10];
    for(int i=0; i<10; i++)
    {
      sprintf_s(stName[i].szFName, "Tom");
      sprintf_s(stName[i].szLName, "Hank");
      LP_ST_NAME pName = new ST_NAME;
      memcpy(pName, &stName[i], sizeof(ST_NAME));
      pList.AddTail(pName);
    }
  9. We’ve successfully store the records. We are going to read and display the record from CPtrList now.
  10. 1
    2
    3
    4
    5
    6
    7
    8
    9
    // Retrieve all data from CPtrList
    if (!pList.IsEmpty())
    {
      for (POSITION pos = pList.GetHeadPosition(); pos != NULL;)
      {
        LP_ST_NAME pNode = (LP_ST_NAME) pList.GetNext(pos);
        printf("%s, %s\n", pNode->szFName, pNode->szLName);
      }
    }
  11. Remove the data from CPtrList is a MUST do job if we are no longer need it. Otherwise, it can cause memory leak in the application.
  12. 1
    2
    3
    4
    5
    6
    // Remove data from CPtrList
    while (!pList.IsEmpty())
    {
      LP_ST_NAME pNode = (LP_ST_NAME) pList.RemoveHead();
      delete pNode;
    }