Are negative array indexes allowed in C?

后端 未结 8 2330
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:56

I was just reading some code and found that the person was using arr[-2] to access the 2nd element before the arr, like so:

|a|b|c|         


        
8条回答
  •  情书的邮戳
    2020-11-22 14:52

    About why would someone want to use negative indexes, I have used them in two contexts:

    1. Having a table of combinatorial numbers that tells you comb[1][-1] = 0; you can always check indexes before accessing the table, but this way the code looks cleaner and executes faster.

    2. Putting a centinel at the beginning of a table. For instance, you want to use something like

       while (x < a[i]) i--;
      

    but then you should also check that i is positive.
    Solution: make it so that a[-1] is -DBLE_MAX, so that x<a[-1] will always be false.

提交回复
热议问题