I am trying to write a function that reads numbers out of a string of comma separated values. The first function is:

unsigned get_frame(unsigned &index, char input[])
 {
  const comma=',';
  char *letter;
  char *accum="";
  unsigned out;
  while (input[index]!=comma)
   {
    *letter=input[index];
    strcat(accum,letter);
    index++;
   };
   out=atoi(accum);
   index++;
   return(out);
 };

This function reads the string "input" until it finds a comma, then returns the value of the numbers it just read as a unsigned integer. This works fine. However, when I repeat the function to read the next number as a float, the problems occur. Here is the next function:

float get_matrix(unsigned &index, char input[])
 {
  const comma=',';
  char *letter;
  char *accum="";
  float out;
   while (input[index]!=comma)
   {
    *letter=input[index];
    strcat(accum,letter);
    index++;
   };
   out=atof(accum);
   index++;
   return(out);
 };

As you can see, it's the same function, this time using atof and float. But, the second function does not work. The string accumulator "accum" starts with a long string of nonsense characters that do not go away.

I don't know where they come from, or how to deal with them. Why does this function work the first time and not the second?

Any help will be appreciated.

Both functions are broken in quite a few ways

>const comma=',';
C++ doesn't support implicit int.

>char *accum="";
There are two serious problems here. First, you're not allowed to modify the contents of a string literal, but that's precisely what you're trying to do. Second, a pointer doesn't imply infinite memory. If you want to copy characters to accum, you have to allocate enough memory to do so.

>*letter=input[index];
letter doesn't point anywhere meaningful, so dereferencing it is wrong.

>strcat(accum,letter);
This is wrong in so many ways. I listed two of them when looking at your declaration of accum, but the fact that letter is not a string (because it's not terminated with a '\0' character) means that you can't predict how many characters strcat will attempt to copy.

I'm seeing a fairly fundamental misunderstanding about how memory, pointers and C-style strings work. Maybe you should go back to your books and study up on it a bit.

This article has been dead for over six months. Start a new discussion instead.