title: C String Pointer Function strdel
body: <p>Can someone please explain me why I get "Segmentation fault..." and how to fix it on this bit of code?</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  
  int str_length(char *s) {
      int length = 0, i;
      for(i = 0; *s; i++) {
          s++;
      }
      return i;
  }
  
  char *strdel(char *s, int pos, int n) {
      int i;
      char *p, str[] = "";
      p = str;
      for(i = 0; i &lt; str_length(s) - n + 1; i++)  {
          if(i &gt;= pos) {
              *(p + i) = *(s + i + n);
          }
          else {
              *(p + i) = *(s + i);
          }
      }
      s = str;
      return s;
  }
  
  int main() {
      char *str = "abcdef";
      printf("str_lengh: %d\n", str_length(str));
      printf("strdel: %s\n", strdel(str, 1, 2));
      return 0;
  }
  </code></pre>
  
  <p>And I get this output:</p>
  
  <pre><code>str_lengh: 6
  strdel: adef
  Segmentation fault (core dumped)
  </code></pre>
  
  <p>Also, is there a better way to create a function: 
      char *strdel(char *s, int pos, int n);
  that deletes the n characters from position pos than the one I did?</p>