why is array name a pointer to the first element of the array?

后端 未结 3 1228
盖世英雄少女心
盖世英雄少女心 2020-11-28 13:09

Is this always the case , i mean , that array name is always a pointer to the first element of the array.why is it so?is it something implementation kinda thing or a languag

3条回答
  •  执笔经年
    2020-11-28 13:53

    The historical reason for this behavior can be found here.

    C was derived from an earlier language named B (go figure). B was a typeless language, and memory was treated as a linear array of "cells", basically unsigned integers.

    In B, when you declared an N-element array, as in

    auto a[10];
    

    N cells were allocated for the array, and another cell was set aside to store the address of the first element, which was bound to the variable a. As in C, array indexing was done through pointer arithmetic:

    a[j] == *(a+j)
    

    This worked pretty well until Ritchie started adding struct types to C. The example he gives in the paper is a hypothetical file system entry, which is a node id followed by a name:

    struct {
      int inumber;
      char name[14];
    };
    

    He wanted the contents of the struct type to match the data on the disk; 2 bytes for an integer immediately followed by 14 bytes for the name. There was no good place to stash the pointer to the first element of the array.

    So he got rid of it. Instead of setting aside storage for the pointer, he designed the language so that the pointer value would be computed from the array expression itself.

    This, incidentally, is why an array expression cannot be the target of an assignment; it's effectively the same thing as writing 3 = 4; - you'd be trying to assign a value to another value.

提交回复
热议问题