Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Help on Function Returning a Char pointer. (http://www.go4expert.com/forums/help-function-returning-char-pointer-t18679/)

aravindreigns 24Jul2009 17:12

Help on Function Returning a Char pointer.
 
The function below concatenates two strings and returns a character pointer for the concatenated string.

Code: C++

char* concat(char *s1, const char *s2)
{
    char *t;   
    while(*s1!='\0')
    {
                    *t = *s1;
                    s1++;
                    t++;
    }
    while(*s2!='\0')
    {
                    *t = *s2;
                    s2++;
                    t++;
    }
    *t = '\0';
    return t;
}

But the function here does not display any value and also crashes the program in Dev C++ compiler. (I mean the EXE file is terminated).
Could you kindly tell me what should be done to prevent that and display the correct value string ?

SaswatPadhi 24Jul2009 18:45

Re: Help on Function Returning a Char pointer.
 
Look at the last line of your code. You return the char pointer t, which points to the last cell of the concatenated string, because you have increased t with all those t++.

Correct code will be :
Code: C++

char* concat(const char *s1, const char *s2)
{
    static char T[100]// define T large enough to hold s1 and s2
    char* t = T;
    while(*s1!='\0')
    {
        *t = *s1;
        s1++;
        t++;
    }
    while(*s2!='\0')
    {
        *t = *s2;
        s2++;
        t++;
    }
    *t = '\0';
    return T;
}



All times are GMT +5.5. The time now is 17:07.