1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Help on Function Returning a Char pointer.

Discussion in 'C' started by aravindreigns, Jul 24, 2009.

  1. aravindreigns

    aravindreigns New Member

    Joined:
    Jul 24, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    The function below concatenates two strings and returns a character pointer for the concatenated string.

    Code:
    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 a moderator: Jul 24, 2009
  2. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,343
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    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:
    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;
    }
     

Share This Page