How to create an int pointer on the stack?
void func(int* pa开发者_如何学Goram){};
func(&123); //error: '&' on constant
funct(&int(123)) //error
That's not how pointers work.
You must first allocate memory for your 123, like this:
int x = 123;
func(&x);
You can't take the address of a temporary. Address-of operator (&
) requires an lvalue
as an argument.
void func(int* param){};
int main(){
int k = 123;
func(&k); //fine now
}
Declare an int variable, and then point to it:
int main() {
int x = 123;
func(&x);
}
If you want to declare a pointer on the stack, then declare an int-pointer variable:
int* p = &x;
func(p);
The keyword &
must and should only be applied to actual variables, not operands.
The problem is that you're trying to take the address of an rvalue. Make it an lvalue:
n = 123;
func(&n);
void func(int* param)
{
std::cout << * param << std::endl;
}
int main(int argc, char** argv)
{
int a = 123;
func(&a);
return 0;
}
精彩评论