问题描述
我一直在尝试通过编写简单的代码来理解指针的概念,我遇到了一个错误问题,似乎我无法解决或理解它.
I have been trying to understand pointer concepts by writing simple code,and I got an error problem, and it seems like I couldn't solve it or understand it.
#include <stdio.h>
int *foo(void);
int main(void) {
printf("%d\n", *foo());
return 0;
}
int *foo(void) {
static int num = 1;
++num;
return &(++num);
}
这是错误消息.
error: lvalue required as unary ‘&’ operand
return &(++num);
函数'foo()'返回一个指向int的指针,并且main应该是使用*运算符打印返回的int.对于foo()中的静态num,我认为通过放置静态限定符,num不再是临时变量,因此&"可用于num.
Function 'foo()' returns a pointer to int, and main is supposed to beprint the returned int by using * operator. For static num within foo(), I thought that by putting static qualifier, num is not temporary variable anymore, so '&' can be used to num.
推荐答案
相对于前缀增量运算符++
,C和C ++之间存在区别.
There is a difference between C and C++ relative to the prefix increment operator ++
.
在C中,结果是递增后的操作数的新值.因此,在此表达式&(++num)
中,有一种尝试来获取临时对象的地址(右值).
In C the result is the new value of the operand after incrementation. So in this expression &(++num)
there is an atttempt to get the address of a temporary object (rvalue).
在C ++中,程序将是正确的,因为在C ++中,结果是更新的操作数.它是左值.
In C++ the program will be correct because in C++ the result is the updated operand; it is an lvalue.
在C中,结果是一个新值,而在C ++中,结果是更新的操作数.
That is in C the result is a new value while in C++ the result is the updated operand.
因此在C语言中,您可能不会例如写
So in C you may not for example write
++++++x;
在C ++中,此表达式
while in C++ this expression
++++++x;
是正确的,您可以将一元运算符&
应用于类似这样的表达式
is correct and you may apply the unary operator &
to the expression like
&++++++x;
要使函数在C语言中正确无误,您必须将应用的运算符分开,例如
To make the function correct in C you have to separate the applied operators like
int *foo(void) {
static int num = 1;
++num;
//return &(++num);
++num;
return #
}
这篇关于关于错误的困惑:要求左值为一元'&'操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!