Declaring type of pointers?

前端 未结 10 2060
花落未央
花落未央 2020-12-01 05:20

I just read that we need to give the type of pointers while declaring them in C (or C++) i.e.:

int *point ;

As far as I know, pointers sto

10条回答
  •  离开以前
    2020-12-01 05:51

    Because:

    1. addresses to different types don't need to have the same size. The standard explicitly specifies so (C 2011 standard (online draft), 6.2.5/28).
    2. type-safety: this allows the compiler to detect when you provide an incompatible pointer to a function, or in an assignment. This in turn prevents ugly situations where you mess up the argument order to a function.
    3. the compiler needs to know the type when the pointer is dereferenced.
    4. to do pointer arithmetic the size of the object pointed to needs to be known and thus its type.

    The last two points don't apply to void pointers, which is why they cannot by dereferenced and no pointer arithmetic may be done on them. The standard specifies that a void pointer must be big enough to hold any kind of pointer (except function pointers, which are a different story altogether) and that assignment to and from void pointers may be made without casts (at least in C, in C++ casts are always needed).

提交回复
热议问题