问题描述
为什么不能使用返回指针作为左值的函数?
例如这个函数可以工作
int * function()
{
int * x;
return x;
int main()
{
int * x = function();
x = new int(9);
}
但不是这个
int * function()
{
int * x;
return x;
}
int main()
{
int * x;
function()= x;
}
-
虽然我可以使用指针变量作为左值,为什么我不能使用返回指针作为左值的函数?
-
另外,当函数返回一个
>
refernce,而不是一个指针,那么
就成为一个有效的左值。
您的第一个示例并不能解释您为什么认为它确实如此。您首先将函数调用的结果存储在变量x中,然后使用新创建的数组覆盖x的值。 *(function())= 5应正确地尝试将5写入由函数内部的局部变量x指定的随机存储单元。
示例:
int x;
int * function()
{
return& x;
int main()
{
*(function())= 5;
printf(%d \\\
,x);
}
Why cant I used a function returning a pointer as a lvalue?
For example this one works
int* function()
{
int* x;
return x;
}
int main()
{
int* x = function();
x = new int(9);
}
but not this
int* function()
{
int* x;
return x;
}
int main()
{
int* x;
function() = x;
}
While I can use a pointer variable as a lvalue, why can't I use a function returning a pointer as a lvalue?
Also, when the function returns arefernce, instead of a pointer, thenit becomes a valid lvalue.
Your first sample doesn't do why I think you think it does. You first store the result of the function call in the variable x and then you override x's value with the newly created array. *(function()) = 5 should properly try to write 5 to some random memory location specified by the local variable x inside your function.
Sample:
int x;
int* function()
{
return &x;
}
int main()
{
*(function()) = 5;
printf("%d\n", x);
}
这篇关于使用函数返回指针作为LValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!