Help on Function Returning a Char pointer.

aravindreigns's Avatar, Join Date: Jul 2009
Newbie Member
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 ?

Last edited by SaswatPadhi; 24Jul2009 at 18:33.. Reason: Code blocks
0
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
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;
}