A Character-to-String Function

Modern programming languages have libraries rich with routines, functions, and methods — plenty to pull together and craft the code you want without getting into the nitty-gritties or reinventing the wheel. As a mid-level language, C often requires that you craft your own functions, a task I undertake with eager glee.

For example, from last week’s Lesson, I could really use a function that generates a string of a single character at a given length. You pass the function two arguments: the character and the length desired. I call this function chrstr() and it’s included in the updated Christmas tree code shown below.

2022_12_31-Lesson.c

#include <stdio.h>
#include <stdlib.h>

/* return a string of character c
   length len */
char *chrstr(char c, int len)
{
    char *s;
    int x;

    /* quick test for null or bad arguments */
    if( c=='\0' || len<=0 )
        return(NULL);        /* return NULL on error */

    /* allocate storage */
    s = malloc( len * sizeof(char) + 1 );    /* +1 for the null char */
    /* test for memory error */
    if( s==NULL )            /* return NULL on error */
        return(s);

    /* fill the string */
    for( x=0; x<len; x++ )
        *(s+x) = c;
    
    /* cap the string */
    *(s+x) = '\0';

    return(s);
}

int main()
{
    int x,stars;
    const int height = 20;    /* 20 rows tall */

    for( x=0,stars=1 ; x<height; x++,stars+=2 )
    {
        /* print the indent */
        printf("%s%s\n",
                chrstr(' ',height-x),
                chrstr('*',stars)
              );
    }

    return(0);
}

The chrstr() function’s two arguments are the single character and a length. I could have written this function specifically for the Christmas tree code in the main() function, but I may want to use it again. Therefore some Defense Against the Dark Programming Arts is necessary.

A test is performed to ensure that a valid character (c) is passed and that the length value (len) is greater than zero: if( c=='\0' || len<=0 ) Upon failure, the function returns a NULL pointer, which can be checked in the calling code.

Next, storage is allocated for the string, which theoretically can be quite huge:

s = malloc( len * sizeof(char) + 1 );

One is added to the string’s length to account for the terminating null character. If allocation fails, NULL is returned — another test.

A for loop then fills the freshly-allocated string with the given character. After the loop is done, the null character is added, properly capping the string. The string’s address is returned. Because the string was allocated in the function, as opposed to using a character array, the memory is retained and the string can be used throughout the code.

Technically the string can be freed after it’s done. But in practice when programmers use a C function that allocates a string rarely do they free it. When the program quits, the storage is released.

In the main() function, the code is modified to reach my goal of outputting the Christmas tree by using a single statement in a loop. The printf() statement is split across several lines to make it more readable. Here is the output:

Leave a Reply