Reputation: 137
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.
Upvotes: 1
Views: 113
Reputation: 3842
When you input -123
, the array is being filled with the characters '-'
, '1'
, '2'
, and '3'
. The array looks like:
arr[0] = '-'
arr[1] = '1'
arr[2] = '2'
arr[3] = '3'
arr[4...BUFSIZ] = ???
As you can see, arr[0]
is the character '-'
, not the integer -1
. The numeric value of '-' (45)
is 3 less than that of '0' (48)
, hence the output of -3
when subtracting from arr[0]
, and the correct output of 1
when you change to arr[1]
. To see the numerical values of all the standard characters on a keyboard, check out http://www.asciitable.com/
As for outputting from the end of the array, I think that is undefined behavior, because you are not actually assigning anything to those indices.
Upvotes: 1