我认为以下代码是正确的,但它并没有起作用。
请帮我确认这两个代码片段是否正确。如果不正确,请指出其中的错误在哪里?
int x, *ra;
&ra = x;
并且
int x, ra;
&ra = x;
请帮我确认这两个代码片段是否正确。如果不正确,请指出其中的错误在哪里?
int x, *ra;
&ra = x;
并且
int x, ra;
&ra = x;
你们两个的表达都是错误的,应该是:
int x, *ra;
ra = &x; // pointer variable assigning address of x
&
是 ampersand,是一个地址运算符(在一元语法中),使用&
可以将变量x
的地址赋给指针变量ra
。
此外,正如您的问题标题所示:将int值分配给地址
。
ra
是一个指针,包含变量x
的地址,因此您可以通过ra
给x
赋予新值。
*ra = 20;
*
(一元语法中)是解引用运算符,它给出存储在地址上的值。int x = 10;
int &ra = x; // reference at time of declaration
x
赋一个新值,语法非常简单,就像我们对值变量所做的那样。ra = 20;
ra
是一个引用变量,我们在将其分配给x
时没有使用&
或*
,但仍然会反映出变化。这就是引用变量的好处:简单易用,可以像指针一样使用!)两者都是不正确的。
当您声明一个指针时,您将其赋值为一个变量的地址。您正在尝试反过来做。正确的方法应该是:
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
这是我的意见。
如果你想了解在C语言中指针的概念,首先需要区分*
这个操作符和*
这个类型限定符/说明符。
在C语言中,*
是一个语法元素,可以扮演两种角色,但永远不会同时发挥作用。它可以作为一种类型限定符:
int a;
int * c = &a;
int * my_function_returning_pointer();
获取正确的整数,作为运算符。(*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 ( i.e *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.