The result of the module is negative

Why is the following C code generating negative numbers as output? And how can I prevent this?

    #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");
            }
    }

      

+3


source to share


1 answer


Take a look at this line of code:

buf[i] = i%256;

      

i % 256

Evaluated here as a value of the type int

. It buf

is however an array char

s, so when a value is assigned to an array, it is truncated to char

. If a modulus result is outside the range of positive values โ€‹โ€‹that can be stored in char

, it can wrap around and be stored instead of a negative number.



In other words, this does not mean that the module has produced a negative value as much as you have stored the result in a type that cannot hold it. Try changing the array to an array int

or an array unsigned char

and see if that fixes something.

Hope this helps!

+7


source







All Articles