[英]C struct return pointer, store in reference
I have a simple question which I am trying to figure out why... 我有一个简单的问题,试图找出原因...
I have a function that returns a struct pointer. 我有一个返回结构指针的函数。 And I have a struct variable 'a'. 我有一个结构变量“ a”。
&a = somefunc(...) // returns a pointer to my struct.
error: lvalue required as left operand of assignment
Why does the above not work, while the following works... 为什么以上方法不起作用,而以下方法却起作用...
struct whatever *b = somefunc(...)
My thinking is, in both cases, I am returning something of type struct whatever. 我的想法是,在两种情况下,我都返回struct类型的东西。
Thanks! 谢谢!
&a
means "give me address of a", which is not a l-value (you cannot assign anything to it). &a
表示“给我一个地址”,它不是l值(您不能为其分配任何内容)。 In second example *b
is a valid l-value 在第二个示例中, *b
是有效的l值
You can think of &a
returning 100. You cannot do 100 = something. 您可以想到&a
返回100。您不能做100 =某事。 While b
is a valid variable (of type pointer). 而b
是有效的变量(类型为指针)。
只有指针可以保存地址,在第一种情况下,您尝试将地址分配给地址,即将值分配给值。
The address of
operator &
yields an rvalue
which is the memory address of its operand. 运算符&
的address of
产生一个rvalue
,该rvalue
是其操作数的内存地址。 You can't have an rvalue on the left side of an assignment. 作业的左侧不能有右值。 Hence you need an lvalue
and to store the address of a variable, you need a pointer type variable. 因此,您需要一个lvalue
并且要存储变量的地址,您需要一个指针类型的变量。
struct mystruct {
int marks;
char grade;
};
// a is of type struct mystruct.
// stores a value of this type
struct mystruct a;
// b is pointer to struct mystruct type.
// stores the address of a variable of this type.
struct mystruct *b;
b = &a; // assign b the address of a
&a
means address of a
. &a
表示address of a
。 You can't assign anything to an address of something
. 您不能将任何东西分配给address of something
的address of something
。 Think of it as your email address in general -- people can ask you for it and they can use it after you gave it to them, but they can't change it. 通常将其视为您的电子邮件地址-人们可以要求您提供它,并且在您将其提供给他们后可以使用它,但是他们无法更改它。
On the other hand, *b
is a variable that contains an address of struct whatever
. 另一方面, *b
是a variable that contains an address of struct whatever
。 That's something that you can store a value in. In email terms that would be a whiteboard with dedicated space where you write your email address. 您可以在其中存储值。用电子邮件术语来说,这是一块白板,上面有专用的空间,您可以在其中写下您的电子邮件地址。 If someone wants to change it, they can do it. 如果有人想更改它,他们可以做到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.