Thursday, April 25, 2024
HomeC ProgrammingA Character-to-String Perform | C For Dummies Weblog

A Character-to-String Perform | C For Dummies Weblog


Fashionable programming languages have libraries wealthy with routines, capabilities, and strategies — lots to tug collectively and craft the code you need with out entering into the nitty-gritties or reinventing the wheel. As a mid-level language, C typically requires that you simply craft your individual capabilities, a job I undertake with keen glee.

For instance, from final week’s Lesson, I might actually use a perform that generates a string of a single character at a given size. You move the perform two arguments: the character and the size desired. I name this perform chrstr() and it’s included within the up to date Christmas tree code proven under.

2022_12_31-Lesson.c


#embrace <stdio.h>
#embrace <stdlib.h>


char *chrstr(char c, int len)


int essential()
{
    int x,stars;
    const int peak = 20;    

    for( x=0,stars=1 ; x<peak; x++,stars+=2 )
    {
        
        printf("%spercentsn",
                chrstr(' ',height-x),
                chrstr('*',stars)
              );
    }

    return(0);
}

The chrstr() perform’s two arguments are the one character and a size. I might have written this perform particularly for the Christmas tree code within the essential() perform, however I’ll wish to use it once more. Subsequently some Protection In opposition to the Darkish Programming Arts is critical.

A check is carried out to make sure that a sound character (c) is handed and that the size worth (len) is bigger than zero: if( c=='' || len<=0 ) Upon failure, the perform returns a NULL pointer, which may be checked within the calling code.

Subsequent, storage is allotted for the string, which theoretically may be fairly big:

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

One is added to the string’s size to account for the terminating null character. If allocation fails, NULL is returned — one other check.

A for loop then fills the freshly-allocated string with the given character. After the loop is finished, the null character is added, correctly capping the string. The string’s deal with is returned. As a result of the string was allotted within the perform, versus utilizing a personality array, the reminiscence is retained and the string can be utilized all through the code.

Technically the string may be freed after it’s executed. However in apply when programmers use a C perform that allocates a string hardly ever do they free it. When this system quits, the storage is launched.

Within the essential() perform, the code is modified to achieve my purpose of outputting the Christmas tree through the use of a single assertion in a loop. The printf() assertion is cut up throughout a number of traces to make it extra readable. Right here is the output:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments