title: Fastest way to convert 2D-array into char* array and copy a char into end of string
body: <p>I'm looking for an example code or how to improve the below code (that it's very slow IMO, but it's that I can write) to the fastest way to convert an 2D-array into a <code>char*</code> and copy a <code>char</code> to it.</p>
  
  <pre><code>char*
  join(int c, size_t arrsize, const char* arr[])
  {
    char *buf, *tbuf, *val;
    size_t i, vsize, total;
  
    buf = malloc(1);
    for(i = total = 0; i &lt; arrsize; ++i) {
      val = arr[i];
      vsize = strlen(val);
  
      if((tbuf = realloc(buf, total + vsize + 2)) == NULL) {
        if(buf != NULL)
          free(buf);
        return NULL;
      }
  
      buf = tbuf;
  
      memcpy(buf + total, val, vsize);
      total += vsize;
  
      buf[total] = c;
      total += 1;
    }
  
    buf[total] = '\0';
    return buf;
  }
  </code></pre>
  
  <p>calling </p>
  
  <pre><code>const char *foo[] = { "a", "b", "c"};
  char *baa = join(' ', 2, foo); //a b c
  if(baa) {
    printf("%s\n", baa);
      free(baa);
  } else {
      printf("No memory\n");
  }
  </code></pre>
  
  <p>How can this be optimised?</p>