int *ptr;
&
) operator. Yes, we use this same symbol for creating reference variables, but you can read the differences by clicking here.x
:
int x;
x
a value of 928
:
x = 928;
x
somewhere it would be like writing the value 928
since that's what x
's value is. But we can't give a pointer 928
because it would interpret that as the memory address you want it to point to (which is most likely NOT where x
is located in memory). So we put the ampersand in front of x
(&x
) and pass that to the pointer variable:
int *ptr; // declare pointer variable of type integer
int x; // declare 'x' as an integer
x = 928; // put value of '928' into 'x'
ptr = &x; // give 'ptr' the memory address of 'x'
If you want to see the difference between putting the ampersand in front and not you can try the following code:
/* -example-source-1------------------------------------------------- */
#include <iostream.h>
void main()
{
int x; // create an integer variable called 'x'
x = 10; // put value of '10' into variable 'x'
cout << "the value of 'x' is " << x << endl
<< "the memory address of 'x' is " << &x << endl;
}
/* ------------------------------------------------------------------ */
*ptr = &x;
ptr = &x;
[type] *[name];
)
)
&
)&x
would be intrepreted as "getting the memory address of x
". But in declaration: int &x
, it is seen as "create a reference variable named". So this (int &x
) is read by the compiler as "create a reference variable named x
".
Page Content & Design ©1998++ By Neil C. Obremski |