title: Segmentation fault. Converting a string to an integer
body: <p>I have a problem where I'm trying to turn a value from an array of string pointers to an integer value: token[1]. However, I get a segmentation fault whenever I don't specify an integer at the first index which in some cases I won't need a number. For example what if I just wanted to type the command: list. I would get a segmentation fault after. How do I store the convert the string value at token[1] to an integer, if an integer is present or not?</p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;ctype.h&gt;
  int main(){
      int ch,  n = 1;
      int i = 0;
      int val = 0;
      char str[512], *token[5], *act_token;
      while(1){
  
              printf("Enter text: ");
              while((ch = getchar()) != '\n')
                      str[i++] = ch;
              str[i] = '\0';
              i = 0;                
  
              printf("string: %s\n", str);
  
              int spaces = 0;
              for(int counter  = 0; counter &lt; strlen(str) + 1; counter++){
                      if(str[counter] == ' '){
                              spaces++;
                      }
              }
              printf("Spaces: %d\n", spaces); 
              strtok(str, " ");
              while(n &lt;= spaces &amp;&amp; (act_token = strtok(NULL, " "))){
                      token[n] = act_token;
                      n++;
  
              }
              token[n] = NULL;
              n = 1;
      //      printf("token[1]: %s\n", token[1]);     
              for(int x = 1; x &lt; spaces+1; x++){
                      printf("token[%d]: %s\n", x, token[x]);
  
              } 
  
              if(isdigit(atoi(token[1])) != 0){
                      val = atoi(token[1]);
              }
              printf("value:%d\n", val);
      }
  
      return 0;
  </code></pre>
  
  <p>}</p>