Search code examples
ccharc-stringsuppercasefunction-definition

How do I append character gotten from loop to a string and return the value of the string as my output


I wanted to return characters as a single string after making each character uppercase in C language (Not using printf or putchar). The aim is to return the value of the string after adding each character

#include <stdio.h>
#include <string.h>

char *my_upcase(char *param_1)
{
    int j = 0;
    char *result = "";
    char *str;
    
    while (j < strlen(param_1))
    {
        char toupper = param_1[j];
        if(toupper >= 'a'){
            // putchar(toupper - 32);
            *str = toupper - 32;
            strncat(result, &toupper -32, 1);
            putchar(*str);
        }else {
        // putchar(toupper);
        *str = toupper;
         strncat(result, &toupper, 1);
         putchar(*str);
        }
        j++;
    }
    return result;
}

Solution

  • The function implementation does not make sense.

    Firstly if the function does not change the source string then its parameter should be declared with qualifier const

    char * my_upcase( const char *param_1 );
    

    This declaration

    char *result = "";
    

    declares a pointer to a string ;iteral. You may not change string literals. Any attempt to change a string literal results in undefined behavior.

    This declaration

    char *str;
    

    declares an uninitialized pointer that has an indeterminate value. Dereferencing such a pointer results in undefined behavior.

    You need to allocate dynamically a character array and copy into it characters of the source string converted to the upper case.

    Using the function strncat is inefficient.

    And do not use magic numbers like 32. Instead use the standard C function toupper declared in the header <ctype.h>

    For example the function can be defined the following way

    #include <string.h>
    #include <ctype.h>
    
    //...
    
    char * my_upcase( const char *param_1 )
    {
        char *result = malloc( strlen( param_1 ) + 1 );
    
        if ( result != NULL )
        {
            char *p = result;
    
            while ( ( *p = toupper( ( unsigned char )*param_1 ) ) != '\0' )
            {
                ++p;
                ++param_1;
            }
        }
    
        return result;
    }   
    

    Taking your comment to my answer

    Thank you for your response. However, I am not allowed to change this declaration char * my_upcase( const char *param_1 ); and the platform will not allow toupper method

    it seems the function must change the original passed string. In this case it can be defined the following way

    char * my_upcase( char *param_1 )
    {
        for ( char *p = param_1; *p != '\0'; ++p )
        {
            if ( 'a' <= *p && *p <= 'z' )
            {
                *p = *p - 'a' + 'A';
            }
        }
    
        return param_1;
    }