2

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.

Ant's
  • 13,545
  • 27
  • 98
  • 148

1 Answers1

7

If you want to access the 10th element in an array, you do:

array[9]

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:

array['9']

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.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
  • Actually, every character-encoding scheme that is used by C, '9'-'0' must equal 9. The standard guarantees that: "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous." (The list it's talking about is 0 1 2 3 4 5 6 7 8 9). – Wiz Apr 05 '12 at 05:56
  • why does this code execute and give a result?... Its trying to access some out of bound memory area right? it should crash before that isnt it? – TutuGeorge Apr 05 '12 at 05:56
  • @NOOB: It does, that does not mean it will crash. It's "undefined behaviour". – Michael Foukarakis Apr 05 '12 at 05:58
  • @Ant's: I think NOOB's referring to the out-of-bounds array access. – Michael Foukarakis Apr 05 '12 at 06:04
  • @NOOB: `Its trying to access some out of bound memory area ` How your saying so? As per the answer given, `'9'`-`'0'` should return `9` and yes I can access it within the array index know? – Ant's Apr 05 '12 at 06:05
  • i was mentionig about this use ndigit['9'] . This i considered as an out of boundary array access. – TutuGeorge Apr 05 '12 at 06:11