Go沒有指針算術,所以它不能訪問這樣的指針pointer[index]
,因爲這意味着*(pointer + index)
。另一個原因是指針不包含索引的限制,如果這樣的訪問是允許的意味着無約束的內存訪問成爲可能。
參考來源
例子
/*
#include <stdlib.h>
struct A {
int a;
};
int fun(struct A** a)
{
struct A* _a = (struct A*)malloc(sizeof(struct A) * 2);
_a[0].a = 50;
_a[1].a = 5;
*a = _a;
return 2;
}
*/
import "C"
import "unsafe"
func main() {
var a *C.struct_A
aLen := C.fun(&a)
if a != nil {
p2 := (*[1 << 30]C.struct_A)(unsafe.Pointer(a))
for i := 0; i < int(aLen); i++ {
println(p2[i].a)
}
C.free(unsafe.Pointer(a))
}
}
運行輸出
50
5