{"id":33032,"date":"2023-02-03T23:23:25","date_gmt":"2023-02-03T17:53:25","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/"},"modified":"2023-02-03T23:23:25","modified_gmt":"2023-02-03T17:53:25","slug":"solved-returning-string-in-c-function-closed","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/","title":{"rendered":"[Solved] returning string in C function [closed]"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-39156477\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"39156477\" data-parentid=\"39152027\" data-score=\"0\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>The idea is not that bad, the main errors are the mix-up of numerical digits and characters as shown in the comments.<\/p>\n<p>Also: if you use dynamic memory, than use dynamic memory. If you only want to use a fixed <em>small<\/em> amount you should use the stack instead, e.g.: <code>c[100]<\/code>, but that came up in the comments, too. You also need only one piece of memory. Here is a working example based on your code:<\/p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\/\/ ALL CHECKS OMMITTED!\nchar *countAndSay(int A)\n{\n  int k, count, j;\n  \/\/ \"i\" gets compared against the output of\n  \/\/ strlen() which is of type size_t\n  size_t i;\n  char a;\n\n  \/\/ Seed needs two bytes of memory \n  char *c = malloc(2);\n  \/\/ Another pointer, pointing to the same memory later.\n  \/\/ Set to NULL to avoid an extra malloc()\n  char *temp = NULL;\n  \/\/ a temporary pointer needed for realloc()-ing\n  char *cp;\n  \/\/ fill c with seed\n  c[0] = '1';\n  c[1] = '\\0';\n  if (A == 1) {\n    return c;\n  }\n  \/\/ assuming 1-based input, that is: the first \n  \/\/ entry of the sequence is numbered 1 (one)\n  for (k = 2; k &lt;= A; k++) {\n    \/\/ Memory needed is twice the size of\n    \/\/ the former entry at most.\n    \/\/ (Averages to Conway's constant but that\n    \/\/ number is not usable here, it is only a limit)\n    cp = realloc(temp, strlen(c) * 2 + 1);\n    temp = cp;\n    for (i = 0, j = 0; i &lt; strlen(c); i++) {\n      \/\/printf(\"A i = %zu, j = %zu\\n\",i,j);\n      a = c[i];\n      count = 1;\n      i++;\n      while (c[i] != '\\0') {\n        if (c[i] == a) {\n          count++;\n          i++;\n        } else {\n          i--;\n          break;\n        }\n      }\n      temp[j++] = count + '0';\n      temp[j++] = a;\n      \/\/printf(\"B i = %zu, j = %zu\\n\",i,j-1)\n      \/\/printf(\"B i = %zu, j = %zu\\n\",i,j);\n    }\n    temp[j] = '\\0';\n    if (k &lt; A) {\n      \/\/ Just point \"c\" to the new sequence in \"temp\".\n      \/\/ Why does this work and temp doesn't overwrite c later?\n      \/\/ Or does it *not* always work and fails at one point?\n      \/\/ A mystery! Try to find it out! Some hints in the code.\n      c = temp;\n      temp = NULL;\n    }\n    \/\/ intermediate results:\n    \/\/printf(\"%s\\n\\n\",c);\n  }\n  return temp;\n}\n\nint main(int argc, char **argv)\n{\n  \/\/ your code goes here\n  char *c = countAndSay(atoi(argv[1]));\n  printf(\"%s\\n\", c);\n  free(c);\n  return 0;\n}\n<\/code><\/pre>\n<p>To get a way to check for sequences not in the list over at <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/oeis.org\/A005150\">OEIS<\/a>, I rummaged around in my attic and found this little &#8220;gem&#8221;:<\/p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;limits.h&gt;\n\nchar *conway(char *s)\n{\n  char *seq;\n  char c;\n  size_t len, count, i = 0;\n\n  len = strlen(s);\n  \/*\n   * Worst case is twice as large as the input, e.g.:\n   * 1 -&gt; 11\n   * 21 -&gt; 1211\n   *\/\n  seq = malloc(len * 2 + 1);\n  if (seq == NULL) {\n    return NULL;\n  }\n  while (len) {\n    \/\/ counter for occurrences of ...\n    count = 0;\n    \/\/ ... this character\n    c = s[0];\n    \/\/ as long as the string \"s\" \n    while (*s != '\\0' &amp;&amp; *s == c) {\n      \/\/ move pointer to next character\n      s++;\n      \/\/ increment counter\n      count++;\n      \/\/ decrement the length of the string\n      len--;\n    }\n    \/\/ to keep it simple, fail if c &gt; 9\n    \/\/ but that cannot happen with a seed of 1\n    \/\/ which is used here.\n    \/\/ For other seeds it might be necessary to\n    \/\/ use a map with the higher digits as characters.\n    \/\/ If it is not possible to fit it into a\n    \/\/ character, the approach with a C-string is\n    \/\/ obviously not reasonable anymore.\n    if (count &gt; 9) {\n      free(seq);\n      return NULL;\n    }\n    \/\/ append counter as a character\n    seq[i++] = (char) (count + '0');\n    \/\/ append character \"c\" from above\n    seq[i++] = c;\n  }\n  \/\/ return a proper C-string\n  seq[i] = '\\0';\n  return seq;\n}\n\n\nint main(int argc, char **argv)\n{\n  long i, n;\n  char *seq0, *seq1;\n\n  if (argc != 2) {\n    fprintf(stderr, \"Usage: %s n&gt;0\\n\", argv[0]);\n    exit(EXIT_FAILURE);\n  }\n  \/\/ reset errno, just in case\n  errno = 0;\n  \/\/ get amount from commandline\n  n = strtol(argv[1], NULL, 0);\n  if ((errno == ERANGE &amp;&amp; (n == LONG_MAX || n == LONG_MIN))\n      || (errno != 0 &amp;&amp; n == 0)) {\n    fprintf(stderr, \"strtol failed: %s\\n\", strerror(errno));\n    exit(EXIT_FAILURE);\n  }\n\n  if (n &lt;= 0) {\n    fprintf(stderr, \"Usage: %s n&gt;0\\n\", argv[0]);\n    exit(EXIT_FAILURE);\n  }\n  \/\/ allocate space for seed value \"1\" plus '\\0'\n  \/\/ If the seed is changed the limit in the conway() function\n  \/\/ above might need a change.\n  seq0 = malloc(2);\n  if (seq0 == NULL) {\n    fprintf(stderr, \"malloc() failed to allocate a measly 2 bytes!?\\n\");\n    exit(EXIT_FAILURE);\n  }\n  \/\/ put the initial value into the freshly allocated memory \n  strcpy(seq0, \"1\");\n  \/\/ print it, nicely formatted\n  \/*\n   * putc('1', stdout);\n   * if (n == 1) {\n   * putc('\\n', stdout);\n   * free(seq0);\n   * exit(EXIT_SUCCESS);\n   * } else {\n   * printf(\", \");\n   * }\n   *\/\n  if (n == 1) {\n    puts(\"1\");\n    free(seq0);\n    exit(EXIT_SUCCESS);\n  }\n  \/\/ adjust count\n  n--;\n  for (i = 0; i &lt; n; i++) {\n    \/\/ compute conway sequence as a recursion\n    seq1 = conway(seq0);\n    if (seq1 == NULL) {\n      fprintf(stderr, \"conway() failed, probably because malloc() failed\\n\");\n      exit(EXIT_FAILURE);\n    }\n    \/\/ make room\n    free(seq0);\n    seq0 = NULL;\n    \/\/ print sequence, comma separated\n    \/\/ printf(\"%s%s\", seq1, (i &lt; n - 1) ? \",\" : \"\\n\");\n    \/\/ or print sequence and length of sequence, line separated\n    \/\/ printf(\"%zu: %s%s\", strlen(seq1), seq1, (i &lt; n-1) ? \"\\n\\n\" : \"\\n\");\n    \/\/ print the endresult only\n    if (i == n - 1) {\n      printf(\"%s\\n\", seq1);\n    }\n    \/\/ reuse seq0\n    seq0 = seq1;\n    \/\/ not necessary but deemed good style by some\n    \/\/ although frowned upon by others\n    seq1 = NULL;\n  }\n  \/\/ free the last memory\n  free(seq0);\n  exit(EXIT_SUCCESS);\n}\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved returning string in C function [closed] <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] The idea is not that bad, the main errors are the mix-up of numerical digits and characters as shown in the comments. Also: if you use dynamic memory, than use dynamic memory. If you only want to use a fixed small amount you should use the stack instead, e.g.: c[100], but that came up &#8230; <a title=\"[Solved] returning string in C function [closed]\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\" aria-label=\"More on [Solved] returning string in C function [closed]\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[324,472,362],"class_list":["post-33032","post","type-post","status-publish","format-standard","hentry","category-solved","tag-c","tag-char","tag-string"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] returning string in C function [closed] - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] returning string in C function [closed] - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] The idea is not that bad, the main errors are the mix-up of numerical digits and characters as shown in the comments. Also: if you use dynamic memory, than use dynamic memory. If you only want to use a fixed small amount you should use the stack instead, e.g.: c[100], but that came up ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2023-02-03T17:53:25+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] returning string in C function [closed]\",\"datePublished\":\"2023-02-03T17:53:25+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\"},\"wordCount\":117,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"c++\",\"char\",\"string\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\",\"name\":\"[Solved] returning string in C function [closed] - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2023-02-03T17:53:25+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] returning string in C function [closed]\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] returning string in C function [closed] - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] returning string in C function [closed] - JassWeb","og_description":"[ad_1] The idea is not that bad, the main errors are the mix-up of numerical digits and characters as shown in the comments. Also: if you use dynamic memory, than use dynamic memory. If you only want to use a fixed small amount you should use the stack instead, e.g.: c[100], but that came up ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/","og_site_name":"JassWeb","article_published_time":"2023-02-03T17:53:25+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] returning string in C function [closed]","datePublished":"2023-02-03T17:53:25+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/"},"wordCount":117,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["c++","char","string"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/","url":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/","name":"[Solved] returning string in C function [closed] - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2023-02-03T17:53:25+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-returning-string-in-c-function-closed\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] returning string in C function [closed]"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/33032","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=33032"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/33032\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=33032"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=33032"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=33032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}