So I'm fooling around with char arrays conversion and testing now this simple code:
#include <stdio.h>
int main(void) {
char arr[BUFSIZ];
printf("Input: ");
fgets(arr, sizeof(arr), stdin);
int x = arr[0] - '0';
printf("Output: %d\n", x);
}
The output should be value of variable x which is first digit of input.
But, in case of passing negative integer as input I get this:
jharvard@appliance (~/CS50/pset1): ./test
Input: -123
Output: -3
The output should be -1, but is -3. Is this minus has something to do with array index?
I assume this minus forces compiler to make array[-1] index the value of output?
I think that's the point, 'cause after changing the line int x = arr[0] - '0';
to int x = arr[1] - '0';
, I get:
Input: -123
Output: 1
when passing the negative number.
And another example.
When changing that int x line to int x = arr[BUFSIZ - 1] - '0';
I get:
jharvard@appliance (~/CS50/pset1): ./test
Input: -123
Output: -40
jharvard@appliance (~/CS50/pset1): ./test
Input: 123
Output: -40
jharvard@appliance (~/CS50/pset1): ./test
Input: 122
Output: -40
jharvard@appliance (~/CS50/pset1): ./test
Input: 890
Output: -40
No matter if various positive or negative numbers I pass, the output is always -40 in this case.
After changing index, e.g. to int x = arr[BUFSIZ - 2] - '0';
or int x = arr[BUFSIZ - 7] - '0';
I got different output - sometimes positive or negative, but always this particular number gets printed.
BUFSIZ on my PC is 8192 bytes long.