CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 30
  1. #1
    Join Date
    Jul 2009
    Posts
    45

    How to convert string to char *?

    Here is my code:
    Code:
    void func1(char * var1){
    ...
    }
    
    std::string str;
    
    func1( str... /* question here */ );
    How do I convert string to char *? I tried: str.c_str() , but c_str() returns a const. The function changes the string, so that doesn't work for me.

    Is there any better approach?
    Last edited by cpthk; August 18th, 2009 at 06:06 PM.

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: How to convert string to char *?

    Why not change func1 such that it takes a std::string instead?

    If you cannot do that, one solution is to create an array of char of sufficient size, copy over the contents of the std::string (appending a null character), then pass a pointer to the first character of this new array to the function.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    May 2002
    Posts
    1,435

    Re: How to convert string to char *?

    Would this work for you?
    Code:
    void func1(std::string& var1){
    ...
    }
    
    std::string str;
    func1(str);

  4. #4
    Join Date
    Jul 2009
    Posts
    45

    Re: How to convert string to char *?

    sorry, I am not allowed to do that. The function is written by another library. If I change the function, there are hundred of calls I need to update.

    @laserlight
    could you give me a code example?

  5. #5
    Join Date
    May 2007
    Posts
    811

    Re: How to convert string to char *?

    Code:
    void func1(char * var1)
    is exactly like this or:
    Code:
    void func1(const char * var1)
    ?

    If second, then:
    Code:
    std::string str;
    func1(str.c_str());
    if first, then yes, you will need to make temporary char array, copy content into it and pass to function.

  6. #6
    Join Date
    Aug 2007
    Posts
    858

    Re: How to convert string to char *?

    if first, then yes, you will need to make temporary char array, copy content into it and pass to function
    Or you can just do...

    Code:
    string s;
    
    ...
    
    vector<char> temp(s.length() + 1);
    temp.assign(s.begin(), s.end());
    temp.back() = '\0';
    
    func1(&temp[0]);
    ... letting vector cover the allocation for you.

  7. #7
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: How to convert string to char *?

    You can even do it in one line!
    Code:
    vector<char> temp(s.c_str(), s.c_str() + s.length() + 1);
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  8. #8
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: How to convert string to char *?

    I would be wary doing that. Notice the function takes a pointer to non-const. what if the function uses strcat and alters the length of the string that then passes the vectors capacity. Because you are accessing internals of the vector without going through vectors own functions for doing such, it could be problematical imo as the vector will lose internal consistency. This is one occaision where I may choose to manage the memory allocations personally or at the very least make sure I have reserved a fair bit of spare space in the vector. it all depends on exactly what the function will do, to which i could see no details.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  9. #9
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How to convert string to char *?

    If the function needs its argument to be of a certain size, then that's going to be a problem no matter *how* the memory is allocated. So you may as well use a vector sized appropriately.

  10. #10
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: How to convert string to char *?

    Quote Originally Posted by JohnW@Wessex View Post
    You can even do it in one line!
    Code:
    vector<char> temp(s.c_str(), s.c_str() + s.length() + 1);
    Code:
    vector<char> temp(s.begin(), s.end());
    temp.push_back('\0');
    I personally prefer working with "end" iterators then using size type constructs. It is usually safer. forgetting the +1 after length can be easy. Also, its presence is (imo) confusing.

  11. #11
    Join Date
    Apr 1999
    Posts
    27,449

    Re: How to convert string to char *?

    Quote Originally Posted by Russco View Post
    I would be wary doing that. Notice the function takes a pointer to non-const. what if the function uses strcat and alters the length of the string that then passes the vectors capacity.
    How is that any different than allocating too little space using manual memory management?
    Because you are accessing internals of the vector without going through vectors own functions for doing such,
    That is exactly the goal, and that is to use std::vector as just a buffer. It is guaranteed that a vector stores its buffer in contiguous memory, just like any array.
    This is one occaision where I may choose to manage the memory allocations personally or at the very least make sure I have reserved a fair bit of spare space in the vector. it all depends on exactly what the function will do, to which i could see no details.
    You are not improving anything by managing your own memory in this case. Whatever memory you reserved doing manual memory management will encounter the same issues if you don't size your vector appropriately.

    Whatever you did "manually", you can do the same thing with vector. Give us a case where you have managed memory manually (using new[] and delete[]) where a vector couldn't be used.

    Regards,

    Paul McKenzie

  12. #12
    Join Date
    Aug 2009
    Posts
    38

    Re: How to convert string to char *?

    Code:
    #include <string>
    #include <iostream>
    
    void func1(char* var1){}
    
    char* cppstr_to_cstr(const std::string& rstr)
    {
        char* pcstr = (char*) malloc ( rstr.size() + 1 );
        char* pcstr_r = pcstr;
        
        for (int i = 0; i < rstr.size(); i++)
        {
            *pcstr = rstr[i];
            pcstr++;
        }
        *pcstr = '\0';
        
        return pcstr_r;
    }
    
    int main()
    {
        std::string str = "Hello World!";
        
        char* pcstr = cppstr_to_cstr( str );
        
        func1( pcstr );
        
        printf("&#37;s", pcstr);
        
        free ( pcstr );
        pcstr = 0;
        
        system("pause");
    }
    Last edited by mwoods; August 20th, 2009 at 09:12 PM.

  13. #13
    Join Date
    Apr 1999
    Posts
    27,449

    Re: How to convert string to char *?

    Code:
        char* pcstr = (char*) malloc ( rstr.size() + 1 );
    Who is responsible for cleaning up the memory? Why introduce dynamic allocation? The solutions that were given using vector are far superior and safer.
    Code:
    string s;
    //...
    vector<char> temp(s.c_str(), s.c_str() + s.length() + 1);
    char *myptr = &temp[0];
    All of the code you wrote is within those last two lines.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; August 20th, 2009 at 08:49 PM.

  14. #14
    Join Date
    Aug 2009
    Posts
    38

    Re: How to convert string to char *?

    Quote Originally Posted by Paul McKenzie View Post
    Who is responsible for cleaning up the memory?
    Oh my god, I so can't believe you just said that!
    Attached Images Attached Images  

  15. #15
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: How to convert string to char *?

    Quote Originally Posted by mwoods
    Oh my god, I so can't believe you just said that!
    I can't believe that you can't believe that Paul McKenzie wrote that. If ownership is not clear, resource leaks are bound to happen.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Page 1 of 2 12 LastLast

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