{"id":472,"date":"2013-12-28T00:01:13","date_gmt":"2013-12-28T08:01:13","guid":{"rendered":"http:\/\/c-for-dummies.com\/blog\/?p=472"},"modified":"2013-12-14T12:40:14","modified_gmt":"2013-12-14T20:40:14","slug":"build-your-own-string","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=472","title":{"rendered":"Build Your Own String"},"content":{"rendered":"<p>I can think of three rules for concocting your own string in the C language.<br \/>\n<!--more--><br \/>\n&diams; First, the string needs a location in memory.<\/p>\n<p>&diams; Second, the string has to have a given size. Going along with that is typing the size to store <em>char<\/em> variables.<\/p>\n<p>&diams; Finally, the string must have an end.<\/p>\n<p>The string&#8217;s size and its end may seem like the same concepts, but in the C language they&#8217;re not. When you assign storage space for a string, you&#8217;re allocating a given chunk of memory. The string may or may not occupy that entire space, which is why the string must have a definite stopping point.<\/p>\n<p>I&#8217;ve coded my own string functions in C to handle input or manipulate string constants. The C library function I use most often is <em>strcat()<\/em>, which glues two strings together.<\/p>\n<p>Here&#8217;s a chunk of code from a text mode game I wrote. It creates a hidden file in the user&#8217;s home directory to store the high scores table:<\/p>\n<pre><code>strcat(HighScoreFile,homedirprefix);\r\nstrcat(HighScoreFile,\"\/.\");\r\nstrcat(HighScoreFile,HIGH_SCORE_FILENAME);<\/code><\/pre>\n<p>The first line copies the user&#8217;s home directory prefix (obtained from the operating system&#8217;s environment table) into a string buffer, <code>HighScoreFile<\/code>. The second line appends the string constant <code>\/.<\/code> to that buffer. Finally the third line appends the high score filename, referenced by the constant <code>HIGH_SCORE_FILENAME<\/code>, to the buffer. At this point, the string stored in the buffer <code>HighScoreFile<\/code> contains the full pathname to the high score file.<\/p>\n<p>The original string buffer, <code>HighScoreFile<\/code>, is a 256-byte chunk of memory designated as a <em>char<\/em> buffer. Such storage is necessary when you build strings from scratch. The following code shows an example, carefully following the three rules mentioned at the start of this Lesson.<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\nint main()\r\n{\r\n    char *buffer,*b;\r\n\r\n\/* Create a 4-character string buffer *\/\r\n    buffer = (char *)malloc(5 * sizeof(char));\r\n    if(buffer == NULL)\r\n    {\r\n        puts(\"Unable to allocate buffer\");\r\n        exit(1);\r\n    }\r\n\r\n\/* Create the string *\/\r\n    b = buffer;\r\n    *b++ = 'A';\r\n    *b++ = 'B';\r\n    *b++ = 'C';\r\n    *b++ = 'D';\r\n    *b = '\\0';\r\n\r\n\/* Display the string *\/\r\n    printf(\"The string \\\"%s\\\" was created\\n\",buffer);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>Here&#8217;s how the code works with regards to my three rules:<\/p>\n<p>&diams; <em>First, the string needs a location in memory<\/em>.<\/p>\n<p>This job is handled by the <code>buffer<\/code> pointer created at Line 6. The pointer is empty, of course, but it&#8217;s designed to reference the starting address of an array of <em>char<\/em> variables &#8212; a string.<\/p>\n<p>&diams; <em>Second, the string has to have a given size. Going along with that is typing the size to store <\/em>char<em> variables.<\/em><\/p>\n<p>This job is handled by the <em>malloc()<\/em> function at Line 9. Storage space for 5 <em>char<\/em> variables is created. That&#8217;s four characters for the string plus one for the null character, <code>\\0<\/code>. The storage space is typecast to hold <em>char<\/em> variables. That all happens in Line 9.<\/p>\n<p>&diams; <em>Finally, the string must have an end.<\/em><\/p>\n<p>The string is created starting at Line 17. Pointer <code>b<\/code> is initialized to pointer <code>buffer<\/code>&#8216;s address, the start of string storage. Letters A through D are stored in the string; the <code>*b++<\/code> construction stores the character and then increments pointer <code>b<\/code> to reference the next location in the buffer.<\/p>\n<p>Finally, at Line 22, the null character is stored at the end of the string. Variable <code>b<\/code> doesn&#8217;t need to be incremented at that point as it already references the fifth position in the buffer.<\/p>\n<p>Line 25 displays the result.<\/p>\n<pre><code>The string \"ABCD\" was created<\/code><\/pre>\n<p>I&#8217;ve added Figure 1 below to help illustrate how the string is populated. Remember: The key is to cap any string with a null character, <code>\\0<\/code>. If you use the C library string functions, such as <em>strcat()<\/em>, then the null character is dealt with automatically. Do it yourself, however, and you must remember the <code>\\0<\/code>.<\/p>\n<div id=\"attachment_483\" style=\"width: 235px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-483\" src=\"http:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2013\/12\/1228-figure1.png\" alt=\"Figure 1. How pointer b creates the string in memory.\" width=\"225\" height=\"729\" class=\"size-full wp-image-483\" \/><p id=\"caption-attachment-483\" class=\"wp-caption-text\"><strong>Figure 1.<\/strong> How pointer <code>b<\/code> creates the string in memory.<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Just as you know to put a period at the end of a sentence for a spoken language, you must remember that a string of text in C ends with a null character. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=472\">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-472","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\/472","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=472"}],"version-history":[{"count":8,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/472\/revisions"}],"predecessor-version":[{"id":496,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/472\/revisions\/496"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=472"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=472"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=472"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}