Search code examples
csubstringc-stringsfunction-definition

Substring function in C


I'm trying to make substring function in C, which is pretty logical and easy, but for some reason it prints out symbols. I've checked on the internet multiple times, compared to other people's function but I can't find the exact reason why my code doesn't work.

#define MAX 50

char* substring(char string[], int indexBeginning, int indexEnd) {
    const char *result[MAX];
    int n= 0;

    for (int i = indexBeginning; i <= indexEnd; i++) {
        result[n++] = string[i];
    }
    result[n] = '\0';

    return result;
}

Solution

  • This array declaration

    const char *result[MAX];
    

    is incorrect. It seems you mean

    char result[MAX];
    

    But in any case you may not use the array as a returned expression

    return result;
    

    because the array is a local object of the function that will not be alive after exiting the function.

    Also this loop

    for (int i = indexBeginning; i <= indexEnd; i++) {
        result[n++] = string[i];
    }
    

    is unsafe because there is no check that specified indices are valid for the source string.

    And the function itself should be declared like

    char * substring( const char string[], size_t pos, size_t n );
    

    The function can be defined the following way as it is shown in the demonstrative program below.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char * substring( const char s[], size_t pos, size_t n )
    {
        char *result = NULL;
        
        size_t length = strlen( s );
        if ( pos < length )
        {
            n = n <= length - pos ? n : length - pos;
            
            result = malloc( n + 1 );
            
            if ( result != NULL )
            {
                result[n] = '\0';
                
                memcpy( result, s + pos, n );
            }
        }
        
        return result;
    }
    
    int main(void) 
    {
        const char *s = "Hello World!";
        
        char *word = substring( s, 0, 5 );
        
        if ( word ) puts( word );
        
        free( word );
        
        word = substring( s, 6, 5 );
    
        if ( word ) puts( word );
        
        free( word );
        
        return 0;
    }
    

    The program output is

    Hello
    World