Problem with char pointers and strings

This is a discussion on Problem with char pointers and strings within the Windows Programming forums, part of the Platform Specific Boards category; Is there a direct way to get window text to a string variable using GetWindowText() without making any char array?...

  1. #1
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318

    Problem with char pointers and strings

    Is there a direct way to get window text to a string variable using GetWindowText() without making any char array?
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  2. #2
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    Direct - no. Without char array - use(C++) a std::vector, eg:
    Code:
    int len=GetWindowTextLength(hwnd);
    std::vector<TCHAR> tmp(len+1,_T('\0'));
    GetWindowText(hwnd,&tmp[0],len);
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

  3. #3
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Is this okay?
    Code:
    char *buffer;
    string windowtext;
    int winlength=GetWindowTextLength(loggedin[5]);
    buffer=(char*)malloc(winlength);
    GetWindowText(loggedin[5],buffer,winlength);
    windowtext.insert(FileContents.length(),buffer,winlength);
    free(buffer);
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  4. #4
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    Well, it looks to be a mix of c and c++ which is not such a good idea. If it's c-code then you shouldn't have to cast the return value from malloc. If you want to use dynamic memory allocation with c++ then you should prefer 'new' and 'delete' or 'new[]' and 'delete[] for arrays.

    edit: Sorry, I just noticed I forgot to specify the type of std::vector being initialised in my previous post; I've now edited it to correct that omission.
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ (char *) problem?
    By Teegtahn in forum C++ Programming
    Replies: 4
    Last Post: 02-05-2008, 01:23 PM
  2. Help with calloc and pointers to strings.
    By sweetarg in forum C Programming
    Replies: 1
    Last Post: 10-24-2005, 03:28 PM
  3. Concatenation of strings as char pointers
    By sameerc in forum C Programming
    Replies: 11
    Last Post: 05-10-2005, 05:23 PM
  4. Noob trouble: returning strings (pointers to char)
    By SgtMuffles in forum C Programming
    Replies: 4
    Last Post: 02-28-2005, 08:48 PM
  5. Replies: 5
    Last Post: 05-25-2004, 05:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21