将int值分配给地址 [英] Assigning int value to an address

查看:121
本文介绍了将int值分配给地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为以下代码正确无误.

I thought the following codes were correct but it is not working.

int x, *ra;     
&ra  = x;

int x, ra;
&ra = x;

如果这两个代码段都正确,请帮助我.如果没有,您会在其中看到什么错误?

Please help me if both of these code snippets are correct. If not, what errors do you see in them?

推荐答案

您的两个表达式都不正确,应该是:

Your both expressions are incorrect, It should be:

int x, *ra;
ra  = &x;  // pointer variable assigning address of x

&&符是运算符的地址(采用一元语法),使用&您可以将变量x的地址分配到指针变量ra.

& is ampersand is an address of operator (in unary syntax), using & you can assign address of variable x into pointer variable ra.

此外,如您的问题标题所示:Assigning int value to an address.

Moreover, as your question title suggests: Assigning int value to an address.

ra是包含变量x的地址的指针,因此您可以通过ra

ra is a pointer contains address of variable x so you can assign a new value to x via ra

*ra = 20; 

*指针变量(采用一元语法)之前为引用运算符在地址上赋予价值.

Here * before pointer variable (in unary syntax) is deference operator gives value at the address.

因为您也已将问题标记为,所以我认为您对参考变量声明感到困惑是:

Because you have also tagged question to c++ so I think you are confuse with reference variable declaration, that is:

int x = 10;
int &ra = x; // reference at time of declaration 

因此,对于引用变量,如果要为x分配新值,则在语法上非常简单,就像对值变量所做的一样:

Accordingly in case of the reference variable, if you want to assign a new value to x it is very simply in syntax as we do with value variable:

ra = 20;

(注意,即使ra是我们分配给x的引用变量,但没有&*仍会反映出来,这是引用变量的好处:易于使用,可以用作指针!)

(notice even ra is reference variable we assign to x without & or * still change reflects, this is the benefit of reference variable: simple to use capable as pointers!)

记住声明时给定的引用绑定,它不能更改指针变量可以在程序后面指向新变量的位置.

Remember reference binding given at the time of declaration and it can't change where pointer variable can point to the new variable later in the program.

在C中,我们只有指针和值变量,而在C ++中,我们只有指针,引用和值变量.在我的链接答案中,我试图解释指针与参考变量之间的差异 .

In C we only have pointer and value variables, whereas in C++ we have a pointer, reference and value variables. In my linked answer I tried to explain differences between pointer and reference variable.

这篇关于将int值分配给地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆