I'm a beginner in C and I have code like this :
#include <stdio.h>
main()
{
int i;
int ndigit[10] = { [9] = 5 };
printf("%d\n",++ndigit['9']);
}
This prints the value something like this :
-1074223011
But when I change the statement to:
++ndigit['9'-'0']
It is correctly printing the value
6
I wonder why there is a need for adding -0
in my index to make it work properly? And why just mentioning ++ndigit['9']
, doesn't help me?
Thanks in advance.
If you want to access the 10th element in an array, you do:
If you want to access the element at the index which has the value of the character constant for the number
9
+ 1, you do:Due to the way ASCII (and all other character encoding schemes used by C, see Wiz's comment) is defined, the expression
'9' - '0'
actually equals 9, which might confuse you in this case.