Click to See Complete Forum and Search --> : Pointers and dynamic structures


July 27th, 1999, 05:19 PM
I'm trying to get an structure that hold as much data run-time as needed.
So far this below has created new structures of itself, but failed on retriving the data:


class SPtrList
{
public:
SPtrList * next;
char * text;
unsigned index;
} *ListPtr;


void CTeste1Dlg::OnBTAdd1()
{
SPtrList *LocalList;

GetDlgItemText(IDC_EDIT1, m_Edit1);
if (m_Edit1 != _T(""))
{
m_List1.AddString(m_Edit1);
LocalList = (SPtrList *) calloc(1, sizeof(SPtrList));
LocalList->text = (char *) LPCTSTR(m_Edit1);
LocalList->index = gIndex++;
LocalList->next = ListPtr;
ListPtr = LocalList;
}
}

void CTeste1Dlg::OnBtHistory()
{
SPtrList *Lspl;

for( Lspl = ListPtr; Lspl != NULL; Lspl = Lspl->next)
{
m_List1.AddString((LPCTSTR)Lspl->text);
}
}





Solutions?

chiuyan
July 27th, 1999, 05:27 PM
the line
LocalList->text = (char *) LPCTSTR(m_Edit1);
is assigning whatever pointer LPCTSTR(m_Edit1) returns to your text variable, but that pointer is not guaranteed to be there forever, CString can move it anytime it wants (I am assuming thta m_Edit is a CString), so later when you attempt to access that pointer, that string may no longer be there. You should, instead, allocate memory for text & then strcpy m_Edit into it, that way you own that pointer and decide when to free that memory.


HTH
--michael

John Killingbeck
July 27th, 1999, 09:28 PM
Have you tried the MFC collection class templates like CArray, CTypedPtrList, etc.? They do dynamic allocation and offer a variety of functions and features that make dynamic data handling easier, more secure and more standardized than 'roll-your-own'.

NutCracker
July 28th, 1999, 12:16 PM
Thanks both for your tips, the allocation stuff worked fine. I'll see the CTypedPtrList and CArray, although the structure containing
only a char * and an UINT were just to see how to make it work. Tha actual structure will have several kinds of pointers and data.
Nevertheless, thanks.