Equivalence of p[0] and *p for incomplete array types

前端 未结 4 1220
谎友^
谎友^ 2020-12-15 05:22

Consider the following code (it came about as a result of this discussion):

#include 

void foo(int (*p)[]) {          // Argument has incompl         


        
4条回答
  •  自闭症患者
    2020-12-15 05:58

    My C is a bit rusty, but my reading is that when you have an int (*p)[] this:

    (*p)[n]
    

    Says "dereference p to get an array of ints, then take the nth one". Which seems naturally to be well defined. Whereas this:

    p[n][m]
    

    Says "take the nth array in p, then take the mth element of that array". Which doesn't seem well-defined at all; you have to know how big the arrays are to find where the nth one starts.

    This could work for the specific special case where n = 0, because the 0th array is easy to find regardless of how big the arrays are. You've simply found that GCC isn't recognising this special case. I don't know the language spec in detail, so I don't know whether that's a "bug" or not, but my personal tastes in language design are that p[n][m] should either work or not, not that it should work when n is statically known to be 0 and not otherwise.

    Is *p <===> p[0] really a definitive rule from the language specification, or just an observation? I don't think of dereferencing and indexing-by-zero as the same operation when I'm programming.

提交回复
热议问题