Pointers to pointers vs. normal pointers

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

    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.

    Well that's true for the machine (after all roughly everything is a number). But in many languages variables are typed, means that the compiler can then ensure that you use them correctly (types impose a correct context on variables)

    It is true that a pointer to pointer and a pointer (probably) use the same amount of memory to store their value (beware this is not true for int and pointer to int, the size of an address is not related to the size of a house).

    So if you have an address of an address you should use as is and not as a simple address because if you access the pointer to pointer as a simple pointer, then you would be able to manipulate an address of int as if it is a int, which is not (replace int without anything else and you should see the danger). You may be confused because all of this are numbers, but in everyday life you don't: I personally make a big difference in $1 and 1 dog. dog and $ are types, you know what you can do with them.

    You can program in assembly and make what you want, but you will observe how dangerous it is, because you can do almost what you want, especially weird things. Yes modifying an address value is dangerous, suppose you have an autonomous car that should deliver something at an address expressed in distance: 1200 memory street (address) and suppose in that street houses are separated by 100ft (1221 is a non valid address), if you are able to manipulate addresses as you like as integer, you would be able to try to deliver at 1223 and let the packet in the middle of the pavement.

    Another example could be, house, address of the house, entry number in an address book of that address. All of these three are different concepts, different types...

提交回复
热议问题