是否可以在结构中设置结构指针的值?我收到错误消息,无法将 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
}
答案 0 :(得分:1)
因此,在您的示例中,您有指针 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
要解决此问题,您应该将 address 分配给 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
}