title: malloc a 2D array, where each entry is a string, in C
body: <p>I am trying to malloc a 2dimensional array in C, where each entry is a string (so, I suppose, a 3dimensional array). I have read a lot, and this is my attempt. However, I am getting a segmentation fault and I'm really not sure what is wrong. I am quite new to programming, so I apologize if my style is not good!</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  
  int main(int argc, char *argv[])
  {
      double temp, int_check;
      int gen, exit_flag=0, valid_input, valid, i, j;
  
      char ***S;
  
      printf("argc %d\n", argc);
      if(argc &lt; 2)
      {
          printf("Please enter command line arguments of the form: a R where a is the number of generators and R are relators\n");
      exit_flag = 1;
      }
      else
      {
          valid = sscanf(argv[1], "%lg", &amp;temp);
          int_check = temp - (int)temp;
          valid_input = ((valid != 0) &amp;&amp; (valid != EOF)) &amp;&amp; (int_check == 0) &amp;&amp; (temp &gt; 0);
  
          if(!valid_input)
          {
              printf("Invalid input, the number of generators must be an integer &gt; 0\n");
              exit_flag = 1;
          }
          gen = (int)temp;
  
          printf("Number of generators = %d\n", gen);
      }
  
      if(exit_flag==0)
      {
  
          S = (char***)malloc(2*sizeof(char**));      /*Defintes the grid to the size required*/
          if(S == NULL) 
          {
              printf("Cannot allocate memory for the S");
          }
  
          for(i=0; i&lt;2; i++)
          {
              S[i] = (char**)malloc((argc-2)*sizeof(char*));
              if(S[i] == NULL)
              {
                  printf("Cannot allocate memory for the S");
              }
          }                                                   /*Grid finished being given the right size*/
  
          for(i=2; i&lt;argc; i++)                               /*Put the relators in the grid. Make rhs equal 1*/
          {
              strcpy(S[0][i-2], argv[i]);
              strcpy(S[1][i-2], "1");
              printf("relator %s\n", S[0][i-2]);
          }
  
          printf("The array S is\n");
          for(j=0; j&lt;(argc-2); j++)
          {
              for(i=0; i&lt;2; i++)
              {
                  printf(" %s ", S[i][j]);
              }
              printf("\n");
          }
      }
  
      else    /*If the inputs are invalid, exit the program*/
      {
          exit(EXIT_FAILURE);
      }
  
      for(i=0; i&lt;2; i++)
      {
          free(S[i]);
      }
      free(S);
  
      return 0;
  }
  </code></pre>