简体   繁体   English

将结构指针的值设置为结构

[英]set values of a struct pointer to a struct

Is it possible to set the values of a struct pointer in a struct?是否可以在结构中设置结构指针的值? I get an error and cannot typecast myStruct* into myStruct.我收到一个错误,无法将 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
}

So, in your example, you have pointer pS and regular variable S1 .因此,在您的示例中,您有指针pS和常规变量S1

A pointer is a variable that stores the memory address as its value.指针是存储 memory 地址作为其值的变量。

Variable is the name of memory location.变量是 memory 位置的名称。

So, the difference between regular variable is that variable stores value of an object, but pointer stores memory address of an object.因此,常规变量之间的区别在于,变量存储 object 的,而指针存储object 的 memory 地址

There are operators which allow getting object's address and getting object value by it's address:有些运算符允许获取对象的地址并通过其地址获取 object 值:

  • Address-of operator & .运算符的地址& &a will return address of object a . &a将返回 object a地址。
  • Dereference operator * .取消引用运算符* *p will return object stored by address p . *p将返回地址p存储的 object 。

Thus, in your code you should get two errors:因此,在您的代码中,您应该得到两个错误:

pS = S1; // error: Trying to assign struct value to a pointer

S2 = pS; // error: Trying to assign pointer to a struct value

To fix this, you should assign address to a pS and value to S2要解决此问题,您应该将地址分配给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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM