Cannot properly return unsigned char*...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yabansu
    New Member
    • Dec 2006
    • 14

    Cannot properly return unsigned char*...

    Hi everyone,

    I have a problem in returning an unsigned char* from a function.

    In the main function:

    string name = "yabansu";
    unsigned char* arr1 = name.c_str();
    cout << arr1 << endl; //Correctly prints "yabansu"

    Let's say I wrote a function called StringToBytes for doing the same thing above as the following:

    unsigned char* StringToBytes(s tring s)
    {
    cout << (unsigned char*) s.c_str() //Correctly prints "yabansu"
    return (unsigned char*) s.c_str();
    }

    Then I call this function in the main() as below;

    string name = "yabansu";
    unsigned char* arr2 = StringToBytes(n ame);
    cout << arr2 << endl; //prints weird characters instead of "yabansu"

    As you see, nothing is different and the string("yabansu ") can be properly displayed within the StringToBytes() function.

    What could be the reason? Thanks...
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    C and C++ pass actual parameters by value (unless they are C++ reference paramters), e.g.
    Code:
    unsigned char* StringToBytes(string s)
    {
    cout << (unsigned char*) s.c_str() << endl;//Correctly prints "yabansu"
    return (unsigned char*)s.c_str();
    }
    when you call StringToBytes()
    Code:
    unsigned char* arr2 = StringToBytes(name);
    a temporary copy is made of paramter name and this copy is passed into StringToBytes() .
    you can then call the c_str() function which returns a const pointer to the C-style version of the invoking string (the temporary copy).
    then problem is when you return from StringToBytes() the temporary copy of the parameter is destructed and the pointer value returned as a function result is no longer valid, see
    http://msdn2.microsoft .com/en-us/library/3372cxcy(VS.80) .aspx

    you can overcome this problem by passing name as a reference parameter (using &) e.g.
    Code:
    unsigned char* StringToBytes(string &s)
    {
    cout << (unsigned char*) s.c_str() << endl;//Correctly prints "yabansu"
    return (unsigned char*)s.c_str();
    }
    a reference to name is passed and the pointer from s.c_str() is valid on return from the function as it points to a C-style version of name.

    another thing to be careful of is c_str() returns const pointer (the character data pointer to should not be modified) and the cast
    Code:
    return (unsigned char*)s.c_str();
    removes the const so you could do something like
    Code:
    unsigned char* arr2 = StringToBytes(name);
    arr2[3]='c';
    the function result of StringToBytes() should be const qualified

    Comment

    Working...