CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Guest

    Pointers and dynamic structures

    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?



  2. #2
    Join Date
    May 1999
    Location
    Seattle, WA USA
    Posts
    423

    Re: Pointers and dynamic structures

    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

  3. #3
    Join Date
    Jul 1999
    Location
    Uitca, NY
    Posts
    120

    Re: Pointers and dynamic structures

    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'.


  4. #4
    Join Date
    Jul 1999
    Posts
    5

    Re: Pointers and dynamic structures

    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.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured