Originally posted by need some help
Your code looks fairly good but it does have errors in it.
- You read in a line up to a max of 100 chars into a buffer (fine).
- You then assign myrec[i] to the buffer (not good), if you want a record to by copied either create a 2d array and use strncpy() or assign myrec[i] to a newly allocated memory (length is strlen() + 1, where the extra 1 is for the terminating ‘\0’ (NULL) char) and then use strcpy().
- You then print out the record (fine) and increment the index (also fine).
- Your terminating condition is almost right. However, what would happen if there were 11 or more lines? You would get a buffer overrun condition resulting in undefined behaviour (could crash or do random things). Make sure you don’t go beyond the array boundaries.
- What is the final if statement in the loop for? BTW, it is better to use {} for the body of the loop as it reduces inadvertent bugs.
- After the while, in your for loop, you probably want the terminating condition to be j < i, not j < 10. Though I would also recommend using more descriptive variable names for clarity.
Oh, BTW, although j++ is valid and good, I would recommend getting in the habit of using ++j. This is because older compilers may not optimise it very well, and if you move on to C++, iterators are slightly more efficient when using the pre-increment.
If you want more parsing information look here.
Good luck,
Adrian
Comment