我的理解是->运算符是取消引用指向结构的指针并访问一个结构成员的值的简写。
struct point {
int x;
int y;
};
struct point my_point = { 3, 7 };
struct point *p = &my_point; /* p is a pointer to my_point */
(*p).x = 8; /* set the first member of the struct */
p->x = 8; /* equivalent method to set the first member of the struct */
所以上面例子的最后两行是等价的。但我遇到了一些类似的代码:
*p->x = 8
同时使用星号和箭头。这是干什么的?这会尝试";双解引用";指针并分配给内存地址8,还是其他什么?也许是未定义的行为,或者只是编译器错误?
*p->x
等价于*(p->x)
-您正在取消引用p->x
的结果,这意味着x
成员本身具有指针类型。给定一条类似的线
*p->x = 8;
这意味着x
具有类型int *
:
struct foo {
...
int *x;
...
};
请注意,必须先为x
分配一个有效的指针值,然后才能分配给*x
。您可以动态分配内存:
struct foo *p = malloc( sizeof *p ); // dynamically allocate space for 1 instance of struct foo
if ( !p )
// handle allocation failure and exit here.
p->x = malloc( sizeof *p->x ); // dynamically allocate space for 1 int.
if ( !p->x )
// handle allocation failure and exit here.
或者,您可以将x
设置为指向现有的int
对象:
int a;
...
p->x = &a;
*p->x = 8;
对于结构
struct tagp
{
int *x=someaddress;
}p0;
struct tagp *p=&p0;
CCD_ 11访问存储在结构内部的指针x中的地址。它与CCD_ 12和CCD_。
检查此链接