{"id":5687,"date":"2022-12-31T00:01:05","date_gmt":"2022-12-31T08:01:05","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=5687"},"modified":"2022-12-24T11:33:56","modified_gmt":"2022-12-24T19:33:56","slug":"a-character-to-string-function","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=5687","title":{"rendered":"A Character-to-String Function"},"content":{"rendered":"<p>Modern programming languages have libraries rich with routines, functions, and methods &mdash; 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.<br \/>\n<!--more--><br \/>\nFor example, from <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5681\">last week&#8217;s Lesson<\/a>, 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 <em>chrstr()<\/em> and it&#8217;s included in the updated Christmas tree code shown below.<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_12_31-Lesson.c\" rel=\"noopener\" target=\"_blank\">2022_12_31-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\n<span class=\"comments\">\/* return a string of character c\r\n   length len *\/<\/span>\r\nchar *chrstr(char c, int len)\r\n{\r\n    char *s;\r\n    int x;\r\n\r\n    <span class=\"comments\">\/* quick test for null or bad arguments *\/<\/span>\r\n    if( c=='\\0' || len&lt;=0 )\r\n        return(NULL);        <span class=\"comments\">\/* return NULL on error *\/<\/span>\r\n\r\n    <span class=\"comments\">\/* allocate storage *\/<\/span>\r\n    s = malloc( len * sizeof(char) + 1 );    <span class=\"comments\">\/* +1 for the null char *\/<\/span>\r\n    <span class=\"comments\">\/* test for memory error *\/<\/span>\r\n    if( s==NULL )            <span class=\"comments\">\/* return NULL on error *\/<\/span>\r\n        return(s);\r\n\r\n    <span class=\"comments\">\/* fill the string *\/<\/span>\r\n    for( x=0; x&lt;len; x++ )\r\n        *(s+x) = c;\r\n    \r\n    <span class=\"comments\">\/* cap the string *\/<\/span>\r\n    *(s+x) = '\\0';\r\n\r\n    return(s);\r\n}\r\n\r\nint main()\r\n{\r\n    int x,stars;\r\n    const int height = 20;    <span class=\"comments\">\/* 20 rows tall *\/<\/span>\r\n\r\n    for( x=0,stars=1 ; x&lt;height; x++,stars+=2 )\r\n    {\r\n        <span class=\"comments\">\/* print the indent *\/<\/span>\r\n        printf(\"%s%s\\n\",\r\n                chrstr(' ',height-x),\r\n                chrstr('*',stars)\r\n              );\r\n    }\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>chrstr()<\/em> function&#8217;s two arguments are the single character and a length. I could have written this function specifically for the Christmas tree code in the <em>main()<\/em> function, but I may want to use it again. Therefore some Defense Against the Dark Programming Arts is necessary.<\/p>\n<p>A test is performed to ensure that a valid character (<code>c<\/code>) is passed and that the length value (<code>len<\/code>) is greater than zero: <code>if( c=='\\0' || len&lt;=0 )<\/code> Upon failure, the function returns a <code>NULL<\/code> pointer, which can be checked in the calling code.<\/p>\n<p>Next, storage is allocated for the string, which theoretically can be quite huge:<\/p>\n<p><code>s = malloc( len * sizeof(char) + 1 );<\/code><\/p>\n<p>One is added to the string&#8217;s length to account for the terminating null character. If allocation fails, <code>NULL<\/code> is returned &mdash; another test.<\/p>\n<p>A <em>for<\/em> 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&#8217;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.<\/p>\n<p>Technically the string can be freed after it&#8217;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.<\/p>\n<p>In the <em>main()<\/em> function, the code is modified to reach my goal of outputting the Christmas tree by using a single statement in a loop. The <em>printf()<\/em> statement is split across several lines to make it more readable. Here is the output:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2022\/12\/1224-figure1.png\" alt=\"\" width=\"550\" height=\"343\" class=\"aligncenter size-full wp-image-5682\" srcset=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2022\/12\/1224-figure1.png 550w, https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2022\/12\/1224-figure1-300x187.png 300w, https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2022\/12\/1224-figure1-481x300.png 481w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Yet another string function missing from the standard C library is on that converts a single character into a string. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5687\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5687","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5687","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5687"}],"version-history":[{"count":4,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5687\/revisions"}],"predecessor-version":[{"id":5697,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5687\/revisions\/5697"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5687"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5687"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5687"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}