Pointers to pointers vs. normal pointers

前端 未结 12 1272
南旧
南旧 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:33

    The type system of C requires this, if you want to get a correct warning and if you want the code to compile at all. With only one level of depth of pointers you wouldn't know if the pointer is pointing to a pointer or to an actual integer.

    If you dereference a type int** you know the type you get is int* and similarly if you dereference int* the type is int. With your proposal the type would be ambiguous.

    Taking from your example, it is impossible to know whether c points to a int or int*:

    c = rand() % 2 == 0 ? &a : &b;
    

    What type is c pointing to? The compiler doesn't know that, so this next line is impossible to perform:

    *c;
    

    In C all type information is lost after compiling, as every type is checked at compile-time and isn't needed anymore. Your proposal would actually waste memory and time as every pointer would have to have additional runtime information about the types contained in pointers.

提交回复
热议问题