Thread: passsing and returning char array

  1. #1
    Bine
    Guest

    passsing and returning char array

    i have to send char array to a function and then return the char array?so what is the method for an char array of size 15?

  2. #2
    Registered User Azuth's Avatar
    Join Date
    Feb 2002
    Posts
    236
    Do you want to send the contents of the array, or a pointer to it?
    Last edited by Azuth; 02-01-2003 at 05:59 AM.
    Demonographic rhinology is not the only possible outcome, but why take the chance

  3. #3
    Registered User newbie_grg's Avatar
    Join Date
    Jul 2002
    Posts
    77

    ok...

    i think this should do.
    Code:
    char* myfuntion(const char* your_ variable)
    {
    // do stuff
    return (//your char* value here);
    }
    int main(void)
    {
    char v[] = "my array";
    myfunction(v);
    }
    "If knowledge can create problems, it is not through ignorance that we can solve them. "
    -Isaac Asimov(1920-1992)

  4. #4
    Registered User newbie_grg's Avatar
    Join Date
    Jul 2002
    Posts
    77
    incase of 15 elements just do

    Code:
    char v[15] = "my name is fala";
    myfunction(v);
    //same as before.
    "If knowledge can create problems, it is not through ignorance that we can solve them. "
    -Isaac Asimov(1920-1992)

  5. #5
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    Just use std::string. Otherwise your options are to change the string you are passed or return a dynamically allocated string and remember to dealocate it.

    Code:
    // with std::string, copying string
    std::string sixtofour(std::string str) {
        for(int i=0;i<length;++i) {
            if(str[i] = '6') str[i] = '4';
        }
         return str;
    }
    
    char str[15] = "25 or 624";
    cout << sixtofour(str) << endl;
    // prints "25 or 424", str unchanged;
    
    //with char[15]; modifying string
    char * sixtofour(char str[15]) {
       int length = strlen(str);
        for(int i=0;i<length;++i) {
            if(str[i] = '6') str[i] = '4';
        }
        return str;
    }
    
    cout << sixtofour(str) << endl;
    // prints "25 or 424", str="25 or 424" ;
    char *s= sixtofour(str);
    s[3] = '2';  // changes str!
    char *s2 = sixtofour("25 or 6 to 4");// This will often crash many computers
    
    //with char15, copying string.
    char *sixtofour(char str[15]) {
        int length = strlen(str);
        char * copy = new char[length+1];
        copy[0] = '\0';
        strcat(copy,str);
        for(int i=0;i<length;++i) {
            if(copy[i] = '6') copy[i] = '4';
        }
        return copy;  
    }
    
    char *s = sixtofour(str);
    //str unchanged
    s[3] = 2;
    //still unchanged
    //but you need to do some more
    delete [] s;
    // clean up after sixtofour()  solo

Popular pages Recent additions subscribe to a feed