title: Convert string to doubles in C
body: <p>I'm about to implement a dynamic matrix structure (that stores double values) and I got some problems with reading from a file.</p>
  
  <p>The idea is, that the program doesn't know the number of rows and columns in advance. It has to scan the first line in order to find the number of columns.</p>
  
  <p>The problem with simply using <code>fscanf()</code> to scan doubles is, that (as far as I know) it can't differentiate between the newline and space characters, so it would read the whole file as one line.</p>
  
  <p>To fix this I first <code>fscanf()</code> the line character-by-character with a function. It stores the values in a string, that represents exactly one line.</p>
  
  <p>Then I use <code>sscanf()</code> to scan the string for double values and store them in a double array. After the conversion I free the string. This is done in the <em>chararray_to_doublearray</em> function.</p>
  
  <p>Now after a bit of testing I suspect that the <em>chararray_to_doublearray</em> function is not working as intended.</p>
  
  <pre><code>/* Converts a character array to a double array and returns a pointer to it. Frees the space of the character array, as it's no longer needed. */
  double *chararray_to_doublearray(char **chararray)
  {
      int i;
      int elements = 0;
      double *numbers=NULL;
      double newnumber;
      while (sscanf(*chararray, "%lf ", &amp;newnumber) == 1) {
          double* newarray = (double*) malloc(sizeof(double) * (elements+1));
          for (i = 0; i &lt; elements; ++i)
              newarray[i] = numbers[i];
          free(numbers);
          numbers = newarray;
          numbers[elements] = newnumber;
          ++elements;
      }
      free(*chararray);
      return numbers;
  }
  </code></pre>
  
  <p>And the <em>main()</em> function calling only the <em>chararray_to_doublearray</em> function:</p>
  
  <pre><code>main ()
  {
      int i;
      double *numbers;
      char string[50]="12.3 1.2 3.4 4 0.3";
      numbers=chararray_to_doublearray(&amp;string);
      free(numbers)
      return 0;
  }
  </code></pre>
  
  <p><strong>So to summarize:</strong> I couldn't find any good implementation of reading double values from the user (or from a file) until the end of line. This is my implementation.
  Do you have any ideas, what might be wrong with this?</p>
  
  <p>Regards,</p>
  
  <p><em>naroslife</em></p>