PDA

View Full Version : Why am I getting this output?



newport_j
October 12th, 2010, 03:08 PM
fprintf(outfile, "Job type Work stations on route");
for (i = 1; i <= num_job_types; ++i) {
fprintf(outfile, "\n\n%4d ", i);
for (j = 1; j <= num_tasks[i]; ++j)
fprintf(outfile, "%5d", route[i][j])


The above code gives the following output:


Job type Work stations on route

1 3 1 2 5

2 4 1 3

3 2 5 1 4 3n

The very last entry should be 3 not 3n. I cannot understand why.


Any help appreciated.


Newport_j

dwhitney67
October 12th, 2010, 03:21 PM
Consider your indexes; it appears that you are using 1...N, whereas it should probably be 0...(N-1).

In other words, try:


fprintf(outfile, "Job type Work stations on route");

for (i = 0; i < num_job_types; ++i)
{
fprintf(outfile, "\n\n%4d ", i+1);

for (j = 0; j < num_tasks[i]; ++j)
fprintf(outfile, "%5d", route[i][j]);
}

talonmies
October 12th, 2010, 04:12 PM
I don't think indexing is the source of the error - I can't imagine a case where an decimal integer format specifier would ever produce anything other than digits and a sign, out of bounds indexing or not. The n character in the output is being generated by code you are not showing.

VernonA
October 12th, 2010, 07:04 PM
Looping from 1 to N instead of 0..N-1 is such a common error for C newbies that it had to be worth a mention. It was certainly my first thought too when I read the code. If the code is actually correct then it really should have a comment in front of it of the form:

// Array[0] holds <whatever> so loops need to iterate from 1
for example, so other readers know this anti-pattern is intentional.

For debugging the code, do two things. First, puts some visible chars around the %d format codes, so they read, for example, ">>%d<<" or similar. Then add some local code just in front of the loops to set the array elements to their own index values (ie use array[i] = i; code so that element N contains N). Then when the code runs you will know which element is causing the problem and what is being damaged. I suspect you will find that you are stepping off the end of an array, and corrupting one of the format strings, so that, for example, a \n is being replaced by just an 'n', which is then being output.
[Sorry, this last sentence is rubbish, the \n's are replaced with linefeeds at compile time, not runtime, and the string is not stored on the stack anyway. Too many late nights! The rest of the post is OK though.]