Thread: Why the error

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Why the error

    Hi im kinda new to c++ and I can't seem to fix this compile error.
    insert
    Code:
     
    char String::c_str()
    {
       char* cs;
       cs  = new char[length+1];
       strcpy(cs,first);
       return cs;
    }
    I am trying to make a function that takes a String and converts it into a c-style string.
    I keep getting this error though " invalid conversion from 'char*' to 'char'"
    How come this happens and how can it be fixed.

    Thank you all who attempt to help.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Code:
    char String::c_str()
    {
       char* cs;
       cs  = new char[length+1];
       strcpy(cs,first);
       return cs;
    }
    There's your invalid conversion.

    The idea that a c_str function should allocate an unmanaged string buffer doesn't look good, though.

    More commonly this should look like:

    Code:
    const char* String::c_str() const
    {
       return first;
    }
    All the const's so that the user wouldn't be able to mess around with the internal buffer.

    If they now want to store that into a dynamically allocated char array, that's entirely up to them to do in the calling code.

    Otherwise, most often you'd use the c_str method like this:

    Code:
    String s("filename");
    std::ofstream fout(s.c_str());
    When done your way, that would be a memory leak.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Your return type should be char * for this function as that is the type of cs.

    Are you sure you want to return a copy like that? It could be hard to know when cs was deallocated. Make sure you don't leak memory in your string class!

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Works no problem

    Thank you both for the help. It is working fine now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. An error is driving me nuts!
    By ulillillia in forum C Programming
    Replies: 5
    Last Post: 04-04-2009, 09:15 PM
  3. Making C DLL using MSVC++ 2005
    By chico1st in forum C Programming
    Replies: 26
    Last Post: 05-28-2008, 01:17 PM
  4. Connecting to a mysql server and querying problem
    By Diod in forum C++ Programming
    Replies: 8
    Last Post: 02-13-2006, 10:33 AM
  5. Couple C questions :)
    By Divx in forum C Programming
    Replies: 5
    Last Post: 01-28-2003, 01:10 AM