Home > database >  How to return a new string in a function in c?
How to return a new string in a function in c?

Time:12-29

Hello my function should print str1 beginning with str2 (if found), I would like to return a new string (newStr) in the following function but it doesn't work. Some help please

char *myFunction(char *str1, char *str2){
    int strLen;
    int i;
    int j;
    char temp;
    char *newStr;

    strLen=0;
    while(str1[strLen]!='\0'){
        strLen  ;
    }

    i=0;
    j=0;

    while(i<=strLen && str1[i]!='\0'){
        if(str1[i]==str2[j] ){
            newStr[i]=str1[i];
            j  ;
        } else {
          newStr[i]=str1[i];
        }
        i  ;
    }

    return (newStr);
}

CodePudding user response:

char *newStr is uninitialized; you must allocate memory to it, before assigning any value to it.

Allocate memory using malloc or calloc.

CodePudding user response:

For starters the function should be declared like

char * myFunction( const char *str1, const char *str2 );

because the passed strings are not being changed within the function.

If the function has to return a new string then you need to allocate a character array where the string will be stored. However you are using an uninitialized pointer newStr

char *newStr;

The condition in the while loop

while(i<=strLen && str1[i]!='\0'){

does not make a great sense.

The variable j in fact is not used.

The if-else statement within the while loop does not make a sense.

If you are allowed to use standard C string functions then your function can be implemented very easy.

#include <string.h>

char * myFunction( const char *s1, const char *s2 )
{
    char *p = strstr( s1, s2 );

    if ( p != NULL )
    {
        size_t n = strlen( p );

        s1 = p;

        p = malloc( n   1 );

        if ( p != NULL ) memcpy( p, s1, n   1 );
    }

    return p;
} 

Otherwise the function can be defined the following way

char * myFunction( const char *s1, const char *s2 )
{
    size_t n1 = 0;
    while ( s1[n1] )   n1;

    size_t n2 = 0;
    while ( s2[n2] )   n2;

    char *p = NULL;

    if ( !( n1 < n2 ) )
    {
        int found = 0;
        size_t i = 0;

        while ( !found && i < n1 - n2   1 )
        {
            if ( s1[i] == s2[0] )
            {
                size_t j = 1;

                while ( j < n2 && s1[i   j] == s2[j] )   j;
                
                found = j == n2;
            }

            if ( !found )   i;
        }
    
        if ( found )
        {
            p = malloc( n1 - i   1 );
            
            if ( p != NULL )
            {
                size_t j = 0;

                do 
                {
                    p[j] = s1[i   j];
                } while ( p[j  ] != '\0' );
            }
        }       
    }

    return p;
} 
  • Related