Do we have to use fflush everytime? I was trying this program (it was
a code optimization problem) on a sun machine and found that if I
don't use fflush, I am getting garbage output. Can anyone point out
why?
Code---
#include<stdio.h>
int SomeHeight()
{return 18;}
int SomeWidth()
{return 14;}
void Optimize(int SomeData[])
{
int i;
int j;
int RowIndex,Width,Height;
int Value;
int *pSomeData = SomeData;
Height = SomeHeight();
Width = SomeWidth();
//fflush(stdout);
/*The problem is if we remove this line the output has one garbage
value. Please see the output attached. if we dont
comment this line, output is fine. FYI, I am not inputting or
outputting any data*/
RowIndex =0;
int temp;
unsigned int ValueSum;
for(i = 0; i < Height; i += 1)
{
Value = (((i << 1) ) % 4);
ValueSum = 0;
pSomeData = SomeData +RowIndex;
for(j = 0; j < Width; j += 1)
{
*(pSomeData + j) = ValueSum >> 2;
ValueSum += Value;
}
RowIndex = RowIndex + Width;
}
}
int main(int argc,char *argv[])
{
int data[12];
int i,j;
Optimize(data);
for(i = 0; i < SomeHeight(); i += 1)
{
for(j = 0; j < SomeWidth(); j += 1)
{
printf("%d ",data[(i * SomeWidth()) + j] );
}
printf("\n");
}
}
Correct Output With fflush:
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 2 2 3 3 4 4 5 5 6 6
0 0 0 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