title: How to strcpy strings into a two dimension array
body: <p>I run the program in unix. It had segmentation faults. I found out it is from the for loop in read_names function. When I disabled the loop and set i = 0, it worked. However, when I set i = 1 or other number, it showed segmentation fault again. I think the way I store string might be wrong. Could anyone help me figure out this problem? </p>
  
  <p>Besides, could I use strtok to save strings into a two dimension array?</p>
  
  <p>Thank you.</p>
  
  <pre><code>#include &lt;stdio.h&gt; 
  #include &lt;malloc.h&gt;
  #include&lt;string.h&gt;
  
  void alloc(char ***surname, char ***first, char **mid_init, int num);
  void read_names(FILE *inp, char ***surname, char ***first, char **mid_init, int num );
  void free_memory(char ***surname, char ***first, char **mid_init, int num);
  
  int main(int argc, char *argv[])
  {
    int num;
    char **surname, **first, *mid_init;
    FILE *inp = fopen(argv[1], "r");  
    FILE *outp = fopen(argv[2], "w");
    char array[79];
  
    fgets(array, 79, inp);
    fgets(array, 79, inp);
    fgets(array, 79, inp);
    printf("%s", array);
  
    fscanf(inp, "%d", &amp;num);
    fprintf(outp, "%d \n\n", num+10);
  
    alloc(&amp;surname, &amp;first, &amp;mid_init, num);
    read_names(inp, &amp;surname, &amp;first, &amp;mid_init, num);
    free_memory(&amp;surname, &amp;first, &amp;mid_init, num);
  
  
  
    fclose(inp);
    fclose(outp);
  
    return 0;
  }
  
  void alloc(char ***surname, char ***first, char **mid_init, int num)
  {
    int i;
  
    *surname = (char**)malloc(num * sizeof(char*));
    *first = (char**)malloc(num * sizeof(char*));
    *mid_init = (char*)malloc(num * sizeof(char));
  
    for(i=0; i&lt;num; i++)
    {
      (*surname)[i] = (char*)malloc(15*sizeof(char));
      (*first)[i] = (char*)malloc(10*sizeof(char));
    }
  }
  
  void read_names(FILE *inp, char ***surname, char ***first, char **mid_init, int num )
  {
    char *token, array[79];
    char delim[6] = ", .\n";
    int i=0/*, k=0*/;
  
    printf("loop begins\n");
  
    for(i=0; i&lt;num; i++)
    {
        fgets(array, 79, inp);
        printf("%s\n", array);
  
        fgets(array, 79, inp);
        printf("%s\n", array);
  
        token = strtok(array, delim);
        strcpy( *(*(surname+i)+0), token);
        printf("%s   ", *(*(surname+i)+0));
  
        token = strtok(NULL, delim);  
        strcpy( *(*(first+i)+0), token);
        printf("%s  ", *(*(first+i)+0));
  
        token = strtok(NULL, delim);
        **mid_init = token[0];
        printf("%s\n", *mid_init);
  
  
    }
       printf("\nloop ends\n");
  }
  
  void free_memory(char ***surname, char ***first, char **mid_init, int num)
  {
    int i;
  
    free((*mid_init));
  
    for(i=0;i&lt;num;i++)
    {
      free((*surname)[i]);
      free((*first)[i]);
    }
  }
  </code></pre>