When is an array name or a function name 'converted' into a pointer ? (in C)

前端 未结 4 1448
梦毁少年i
梦毁少年i 2020-11-27 16:14

1) Misconception :

  • Whenever an array is declared in C language, a pointer to the first element of the array is created (

4条回答
  •  难免孤独
    2020-11-27 16:35

    The description given in the linked page in the first part of your question is certainly completely incorrect. There is no pointer there, constant or not. You can find the exhaustive explanation of array/function behavior in @KeithThompson's answer.

    On top of that it might make sense to add (as a side note) that arrays implemented as two-part objects - a named pointer pointing to an independent nameless block of memory - are not exactly chimerical. They existed in that specific form in the predecessor of C language - B language. And initially they were carried over from B to C completely unchanged. You can read about it in Dennis Ritchie's "The Development of the C Language" document (see the "Embryonic C" section).

    However, as it is stated in that very document, this kind of array implementation was incompatible with some new features of C language, like struct types. Having two-part arrays inside struct objects would turn such objects into higher-level entities with non-trivial construction. It would also make them incompatible with raw-memory operations (like memcpy and so on). Such considerations are the reason arrays were redesigned from two-part objects into their current single-part form. And, as you can read in that document, the redesign was performed with backward-compatibility with B-style arrays in mind.

    So, firstly, this is why many people get confused by the behavior of C-style arrays, believing that there a pointer hidden in there somewhere. The behavior of the modern C array was specifically designed to emulate/sustain that illusion. And, secondly, some archaic document might still contain leftovers from that "embryonic" era (although, it does not look like the document you linked should be one of them.)

提交回复
热议问题