Results 1 to 6 of 6

Thread: Returning a pointer

  1. #1

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772

    Returning a pointer

    Ok, here is my problem: I am trying to write a function to get the text of an edit box (not the dialog kind). I want to return a char*, but if I free the memory first, there is nothing to return. If I return first, the memory doesn't get freed. What can I do?

    Code:
    char* getText()
    {    
        int len = GetWindowTextLength(m_hParent);
        char* buf = (char*)GlobalAlloc(GPTR, len + 1);
    
        GetWindowText(m_hParent, buf, len + 1);
    
        GlobalFree((HANDLE)buf);
    
        return buf;
    }
    Alcohol & calculus don't mix.
    Never drink & derive.

  2. #2
    jim mcnamara
    Guest
    In general, when you call a routine, it cannot return pointers it creates to memory it allocates.

    Allocate memory either in main() or in the calling function.

    Some programmers create a global buffer for just such use
    Code:
    static char globalbuf[4096];
    
    int main(void){
        
    ..........// stuff
    
    }
    
    char* getText()
    {    
        int len = GetWindowTextLength(m_hParent);
        char* buf = globalbuf;
    
        GetWindowText(m_hParent, buf, len + 1);
    
        GlobalFree((HANDLE)buf);
    
        return buf;
    }

  3. #3
    Zaei
    Guest
    Except remove the GlobalFree() call from the function =).

    Z.

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Why can't you just return a string and be done with it?
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  5. #5

    Thread Starter
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    Ok, but where's the fun in that?
    Alcohol & calculus don't mix.
    Never drink & derive.

  6. #6
    jim mcnamara
    Guest
    Look at C. strcpy(), strstr(), strchr()
    ALL return a pointer to one of the arguments - they don't create a pointer out of thin air. Which is what you're trying to do.

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