指標就在前方不遠處...
今日主題:三星指標
既然有雙星指標,如果願意,也可以再加一顆星。
請看程式碼:
#include <stdio.h>
main()
{
int x = 100;
int *p1 = &x;
int **p2 = &p1;
int ***p3 = &p2;
printf("%p\n", p1); //0x7fff220a1324
printf("%d\n", *p1); //100
printf("%p\n", p2); //0x7fff220a1318
printf("%p\n", *p2); //0x7fff220a1324
printf("%d\n", **p2); //100
printf("%p\n", p3); //0x7fff220a1310
printf("%p\n", *p3); //0x7fff220a1318
printf("%p\n", **p3); //0x7fff220a1324
printf("%d\n", ***p3); //100
}
來個golang版本的.
<pre class="c" name="code">
// threestar
package main
import (
"fmt"
)
func main() {
var x int = 100
var p1 *int = &x
var p2 **int = &p1
var p3 ***int = &p2
fmt.Printf("x = %v\n", x)
fmt.Printf("&x = %v\n", &x)
fmt.Printf("p1 = %v\n", p1)
fmt.Printf("*p1 = %v\n", *p1)
fmt.Printf("p2 = %v\n", p2)
fmt.Printf("*p2 = %v\n", *p2)
fmt.Printf("**p2 = %v\n", **p2)
fmt.Printf("p3 = %v\n", p3)
fmt.Printf("*p3 = %v\n", *p3)
fmt.Printf("**p3 = %v\n", **p3)
fmt.Printf("***p3 = %v\n", ***p3)
}
執行結果:
<pre class="c" name="code">
$ ./threestar
x = 100
&x = 0xf840039100
p1 = 0xf840039100
*p1 = 100
p2 = 0xf840039108
*p2 = 0xf840039100
**p2 = 100
p3 = 0xf840039110
*p3 = 0xf840039108
**p3 = 0xf840039100
***p3 = 100
golang ?? 那是什麼阿
p3 = 0xf840039110
*p3 = 0xf840039108
好好玩喔,看起來p2才2 bytes...(難道是16位元機器)
p2 = 0xf840039108
p3 = 0xf840039110看起來p2才2 bytes
泰大是要考試嗎
0xf840039110 - 0xf840039108 + 1 很明顯是 8 個 bytes 呀
唉,陰溝裏翻船...