Pointers to pointers vs. normal pointers

前端 未结 12 1042
南旧
南旧 2021-01-30 08:33

The purpose of a pointer is to save the address of a specific variable. Then the memory structure of following code should look like:

int a = 5;
int *b = &a;         


        
12条回答
  •  借酒劲吻你
    2021-01-30 08:42

    If the purpose of pointer is just to save the memory address, I think there should be no hierarchy if the address we are going to save refers variable, pointer, double pointer, ... etc. so below type of code should be valid.

    I think here is your misunderstanding: The purpose of the pointer itself is to store the memory address, but a pointer usually as well has a type so that we know what to expect at the place it points to.

    Especially, unlike you, other people really want to have this kind of hierarchy so as to know what to do with the memory contents which is pointed to by the pointer.

    It is the very point of C's pointer system to have type information attached to it.

    If you do

    int a = 5;
    

    &a implies that what you get is a int * so that if you dereference it is an int again.

    Bringing that to the next levels,

    int *b = &a;
    int **c = &b;
    

    &b is a pointer as well. But without knowing what hides behind it, resp. what it points to, it is useless. It is important to know that dereferencing a pointer reveals the type of the original type, so that *(&b) is an int *, and **(&b) is the original int value we work with.

    If you feel that in your circumstances there should be no hierarchy of types, you can always work with void *, although the direct usability is quite limited.

提交回复
热议问题