Why do we have pointers other than void

前端 未结 10 995
攒了一身酷
攒了一身酷 2020-12-30 22:54

I know that we have different pointers like int, float, and char. A void pointer is the only pointer which can hold all o

10条回答
  •  半阙折子戏
    2020-12-30 23:09

    The compiler needs to know the types pointed at otherwise all sorts of code won't work. Consider the following:

    *a = *b + *c;    // Should this add char? int? float?
    s_ptr->x = 0;    // How does the compiler know anything about the structure s_ptr points to?
    a[5] = 0;        // How far is a[5] from a[0]?
    

    Not having types for pointers would be like not having types for anything. The compiler would be completely lost. In short, C and C++ are both strongly typed and this carries over to pointers for fairly obvious reasons.

提交回复
热议问题