title: How do I create a function in C that allows me to split a string based on a delimiter into an array?
body: <p>I want to create a function in C, so that I can pass the function a string, and a delimiter, and it will return to me an array with the parts of the string split up based on the delimiter. Commonly used to separate a sentence into words.</p>
  
  <p>e.g.: <code>"hello world foo"</code> -> <code>["hello", "world", "foo"]</code></p>
  
  <p>However, I'm new to C and a lot of the pointer things are confusing me. I got an answer mostly from <a href="https://stackoverflow.com/questions/11198604/c-split-string-into-an-array-of-strings">this question</a>, but it does it inline, so when I try to separate it into a function the logistics of the pointers are confusing me:</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  void split_string(char string[], char *delimiter, char ***result) {
      char *p = strtok(string, delimiter);
      int i, num_spaces = 0;
  
      while (p != NULL) {
          num_spaces++;
          &amp;result = realloc(&amp;result, sizeof(char *) * num_spaces);
  
          if (&amp;result == NULL) {
              printf("Memory reallocation failed.");
              exit(-1);
          }
  
          &amp;result[num_spaces - 1] = p;
  
          p = strtok(NULL, " ");
      }
  
      // Add the null pointer to the end of our array
      &amp;result = realloc(split_array, sizeof(char *) * num_spaces + 1);
      &amp;result[num_spaces] = 0;
  
      for (i = 0; i &lt; num_spaces; i++) {
          printf("%s\n", &amp;result[i]);
      }
  
      free(&amp;result);
  } 
  
  int main(int argc, char *argv[]) {
      char str[] = "hello world 1 foo";
      char **split_array = NULL;
  
      split_string(str, " ", &amp;split_array);
  
      return 0;
  }
  </code></pre>
  
  <p>The gist of it being that I have a function that accepts a string, accepts a delimiter and accepts a pointer to where to save the result. Then it constructs the result. The variable for the result starts out as NULL and without memory, but I gradually reallocate memory for it as needed.</p>
  
  <p>But I'm really confused as to the pointers, like I said. I know my result is of type <code>char **</code> as a string it of type <code>char *</code> and there are many of them so you need pointers to each, but then I'm supposed to pass the <em>location</em> of that <code>char **</code> to the new function, right, so it becomes a <code>char ***</code>? When I try to access it with <code>&amp;</code> though it doesn't seem to like it.</p>
  
  <p>I feel like I'm missing something fundamental here, I'd really appreciate insight into what is going wrong with the code.</p>