将int值分配给地址

我认为以下代码是正确的,但它不起作用。

int x, *ra; &ra = x; 

 int x, ra; &ra = x; 

如果这两个代码段都正确,请帮助我。 如果没有,你在他们身上看到了什么错误?

你的两个表达都是不正确的,它应该是:

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

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

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

ra是一个包含变量x地址的指针,因此您可以通过rax分配一个新值

 *ra = 20; 

这里*在指针变量之前(在一元语法中)是deference运算符在地址处给出值。

因为您还将问题标记为c ++,所以我认为您对引用变量声明感到困惑,即:

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

因此,在引用变量的情况下,如果要为x分配新值,则在语法中非常简单,就像我们使用值变量一样:

 ra = 20; 

(注意甚至ra是我们分配给x而没有&*仍然改变的参考变量反映,这是参考变量的好处:简单易用,可用作指针!)

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

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

两者都不正确。

声明指针时,为其指定变量的地址。 你正在尝试相反的方式。 正确的方法是:

 int x,*ra; ra = &x; 

这两个原因,就像你在问题中的方式一样,是未定义的行为。

对于第一个,您不初始化指针,这意味着它指向随机位置(如果变量是全局的,则为NULL )。

对于第二个,您尝试更改变量所在的地址,这是不允许的(如果它甚至会编译)。

这是一些带注释的代码:

 int main () { // declare an int variable int x = 0; // declare a pointer to an int variable int *p; // get the memory address of `x` // using the address-of operator &x; // let `p` point to `x` by assigning the address of `x` to `p` p = &x; // assign `x` a value directly x = 42; // assign `x` a value indirectly via `p` // using the dereference operator *p = 0; // get the value of `x` directly x; // get the value of `x` indirectly via `p` // using the dereference operator *p; } 

请注意,不允许取消引用不指向指定类型的有效对象的指针。

所以你通常不应该做以下事情(除非你真的知道你在做什么):

 *(int*)(12345) = 42; // assign an integer value to an arbitrary memory address 

这是我的2美分。

如果您要了解C中的指针。首先区分*运算符和*类型限定符/说明符。

看看在C *是一个syntaxique元素,既可以同时扮演角色,又可以同时扮演角色。 类型限定符:

 int a; int * c = &a; int * my_function_returning_pointer(); 

并获得正确的int。 作为运营商。 ( *c是a的别名)

 *c = 9; 

我承认这很混乱,可能会陷入很多初学者的困境。 确保您在*用作运算符或将其用作类型限定符时识别。

同样的事情适用于&虽然它不常用作类型限定符。

 int & f = returning_a_reference(); int my_function( int & refParam); 

它更常用于获取对象的地址。 因此,它被用作操作员。

 c = &f; 
  case 1: int x,*ra; &ra = x; it is wrong in c, because in c we can point to a memory location by using a pointer ( ie *ra in your case ). this can be done as fallows int x, *ra; x --------- ra=&x; ra --->1000 | value | ---------- NOTE : with out initializing a variable we can't use pointer to hold the address of that variable, so you better to first initialize variable, then set pointer to that memory location. int x, *ra; x=7; ra=&x; Fallowing may be helpful to you: problems(mistake we do ) in handling pointers : 1.) int a ,*p; p=a; // assigning value instead of address. that leads to segmentation fault at run time. 2) int a, *p; &p=a; // look at here wrong assignment 3) char *p="srinivas" strcat(p, "helo" ) ; // we cant add a substring to the constant string. 4) int a=5, *p; p=5; // the pointer here will points to location 5 in the memory, that may damage whole system, be care full in these type of assignments.