請記住struct和指向結構體的指針之間的區別。
讓我們假設一個32位編譯器。
讓我們創建一個結構:
struct point_i {
int x;
int y;
};
這個結構有兩個int成員。每個整數的大小是四個字節,所以結構大小總共爲八個字節。
然後用結構:
strut point_i my_point; // 8 bytes allocated, lets assume that they
// are located at address 0x10000000.
my_point.y = 10;
當你這樣做時,編譯器知道在哪裏my_point位於和它的大小,它也知道在哪裏成員y
相對於該結構。所以它編譯(非常粗略地)喜歡的東西:
MOV [0x10000004], 10 ;; Notice that its 0x10000000 + 4.
;; The first four bytes are X so we skip them
;; to get to Y and put 10 in that memory address.
在另一方面,當你有一個指針:
strut point_i *another_point; // 4 bytes allocated, the pointer size.
// Let's assume in 0x20000000.
another_point = get_random_point(); // Get an address to some random point.
another_point->y = 10; // You have to use -> to reference the member
// because you are not dealing with an struct
// anymore but a *pointer* to said struct.
而且由於編譯器不知道地址,你要提出在那個指針中它必須生成有點不同的代碼。
MOV EBX, [0x20000000] ;; 0x20000000 has your pointer. So we fetch it.
MOV [EBX+4], 10 ;; Dereference the pointer and put 10 in Y.
;; You can see that we now have two memory references,
;; one to get the pointer and another to get where it
;; points to. So it is a layer of indirection.
請注意,這是一個非常簡化的世界觀。編譯器/鏈接器和操作系統解析程序上的內存地址。但它應該澄清在courtain背後發生了什麼。指針取消引用是C的主要部分。
我不想說它是相同的,但它在類似的意義上是存在*隱式*「引用」發生。 – user2864740