- Let’s start the example by creating a Win32 console application from my VS2005 IDE.
- Make sure that we add common header files to support MFC.
- Let’s start the coding by creating a simple struct with 2 char data type variables.
- Let’s create a CPtrList variable now and store 10 records into the memory now.
- We’ve successfully store the records. We are going to read and display the record from CPtrList now.
- 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.

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; |
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); } |
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); } } |
1 2 3 4 5 6 | // Remove data from CPtrList while (!pList.IsEmpty()) { LP_ST_NAME pNode = (LP_ST_NAME) pList.RemoveHead(); delete pNode; } |
Using CPtrList to store data into memory