Why does the following C code produce negative numbers as output? And how do I prevent this from happening?
#include <stdio.h>
int main()
{
int i;
char buf[1024];
for (i = 0; i < 1024; i++)
buf[i] = i%256;
for (i=0; i<1024; i++) {
printf("%d ", buf[i]);
if (i%32==31)
printf("\n");
}
}
Let's look at this line of code:
buf[i] = i%256;
Here, i % 256 is computed as a value of type int. However, buf is an array of chars, so when the value is assigned into the array, it's truncated to a char. If the result of the modulus is outside of the range of positive values that can be stored in a char, it may end up wrapping around and being stored as a negative number instead.
In other words, it's not that the modulus produced a negative value as much as you stored the result in a type that can't hold it. Try changing the array to an int array or unsigned char array and see if that fixes things.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With