Pointers 设置指向结构的结构指针的值
是否可以在结构中设置结构指针的值?我遇到错误,无法将myStruct*键入myStructPointers 设置指向结构的结构指针的值,pointers,Pointers,是否可以在结构中设置结构指针的值?我遇到错误,无法将myStruct*键入myStruct typedef struct { int foo; int bar; } myStruct; int main() { myStruct *pS; myStruct S1 = {0,0}; myStruct S2; pS = S1; S2 = pS; // I get an error there, cannot set struct pointer to a struct
typedef struct {
int foo;
int bar;
} myStruct;
int main() {
myStruct *pS;
myStruct S1 = {0,0};
myStruct S2;
pS = S1;
S2 = pS; // I get an error there, cannot set struct pointer to a struct
}
因此,在您的示例中,有指针
pS
和正则变量S1
指针是将内存地址存储为其值的变量
变量是内存位置的名称
所以,正则变量之间的区别在于,变量存储对象的值,而指针存储对象的内存地址
有一些运算符允许获取对象地址并通过其地址获取对象值:
- 操作员的地址
和
将返回对象&a
的地址a
- 解引用运算符
*
将返回按地址*p
存储的对象p
pS = S1; // error: Trying to assign struct value to a pointer
S2 = pS; // error: Trying to assign pointer to a struct value
要解决此问题,应将地址分配给pS
和值分配给S2
typedef struct {
int foo;
int bar;
} myStruct;
int main() {
myStruct *pS;
myStruct S1 = {0,0};
myStruct S2;
pS = &S1; // getting address of S1
S2 = *pS; // getting value stored by address pS
}