2D array variable pointer confusion

前端 未结 5 2089
日久生厌
日久生厌 2021-01-06 03:35

I have a basic doubt in 2D arrays (C Language). Consider a declaration of a 2D array as follows

int array[3][5];

Now when I do the followin

5条回答
  •  灰色年华
    2021-01-06 04:13

    Arrays are not pointers. Ignore any answer, book, or tutorial that tries to tell you otherwise.

    An expression of array type, in most contexts, is converted (at compile time) into a pointer to the array's first element. The exceptions are:

    • The operand of sizeof (sizeof arr yields the size of the array, not the size of a pointer)
    • The operand of unary & (&arr yields the address of the array, not of its first element -- same memory location, different type). This is particularly relevant to your example.
    • A string literal in an initializer used to initialize an array object (char s[6] = "hello"; doesn't copy the address of the string literal, it copies its value)

    A 2-dimensional array is nothing more or less than an array of arrays. There are other data structures that can be used with the same x[y][z] syntax, but they're not true 2-dimensional arrays. Yours is.

    The [] indexing operator is defined in terms of pointer arithmetic. x[y] means *(x+y).

    The behavior of your code follows from these rules.

    Read section 6 of the comp.lang.c FAQ. It's the best explanation of this stuff I've seen.

    And don't use "%u" to print pointer values; convert to void* and use "%p".

    printf("%p\n", (void*)array);
    printf("%p\n", (void*)*(array));
    

提交回复
热议问题