typecasting

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GajananDonthi
    New Member
    • Mar 2008
    • 1

    typecasting

    hi everyone, can u guide me for the following(C++ beginer)::
    i want to find the string length of str2 after assiging str1 to str2.

    unsigned char* str1 = NULL;
    char* str2 = NULL;
    int istrlength = 0;

    cin>>str1;
    str2 = (char*)str1;
    istrlength = strlen(str2);
    cout<<istrlengt h;
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    #2
    Originally posted by GajananDonthi
    hi everyone, can u guide me for the following(C++ beginer)::
    i want to find the string length of str2 after assiging str1 to str2.

    unsigned char* str1 = NULL;
    char* str2 = NULL;
    int istrlength = 0;

    cin>>str1;
    str2 = (char*)str1;
    istrlength = strlen(str2);
    cout<<istrlengt h;

    problem is in this statement:
    unsigned char* str1 = NULL;

    str1 is pointing to NULL. cin will try to write at this address i.e. 0x0
    If you remove NULL assignment to str1 variable, it will run.
    But this is bad programming,cau se str1 may contain any value that lead to segmentation fault.
    Best option is to use "malloc" and then use cin

    Comment

    • Sick0Fant
      New Member
      • Feb 2008
      • 121

      #3
      I think you're supposed to at least declare a length or use dynamic memory allocation.

      Secondly, I don't think that the assignment operator is overloaded for char*. You have to use strcpy(chr *, const char*).

      Comment

      Working...