pointers - notes
pointers - notes
pointers - notes
INTRODUCTION
Computer memory can be imagined as a very large array of
bytes. For example, a computer with 256 MB of RAM (256
megabytes of ( random-access memory) actually contains an
array of 268,435,456 (2^28) bytes.
As an array, these bytes are indexed from 0 to 268,435,455.
The index of each byte is its memory address. So a 256 MB
computer has memory addresses ranging from 0 to 268,435,455,
which is 0x00000000 to 0x0fffffff in hexadecimal .
Program#1
The two identifiers n and rn are different names for the same
variable; they always have the same value.Decrementing n
changes both n and rn to 43. Doubling rn increases both n and
rn to 86.
int& rn=44; // ERROR: 44 is not a variable!
Program#3
POINTERS
Program#4
int* pn = &n
The variable n is initialized to 44. Its address is
0x0064fddc.
The variable pn is initialized to &n which is the address of
n, so the value of pn is 0x0064fddc
But pn is a separate variable . it has the distinct address
0x0064fde0.
The variable pn is called a “pointer to n”
because its value “points”to the location of another
value.
The value of a pointer is an address.
A pointer can be thought of as a “locator”: it locates a
object.
THE DEREFERENCE OPERATOR(symbol *)
If pn points to n, the expression *pn evaluates to the value of n.
This evaluation is called “dereferencing the pointer” pn, and the
symbol * is called the dereference operator.
Program#5
Note:
1. int n= 22;
int* p = &n;
cin >>p; error (the value of p is address.)
2.
Pointer Arithmetic
Program#8(Pointers_3)
explaination
The pointer p is initialized to point to s [ 3 ] which
contains ' D', and then the pointer q is initialized to point to
s[6] which contains ' G'. Decrementing p makes it point to
s [2] which contains 'C, and then incrementing q makes it
point to s [ 7 ] which contains ' H'. Now q contains an
address which is 5 bytes higher than the address in p, so q - p
evaluates to 5.
Program#11(Pointers_6)
Passing argument to function by reference with
Pointer
Program#12// Passing argument to function by reference with Pointer
// Cube a variable using pass-by-reference with a pointer argument.
#include <iostream>
using namespace std;
void cubeByReference( int * ); // prototype
int main()
{
int number = 5;
cout << "The original value of number is " << number;
cubeByReference( &number ); // pass number address to cubeByReference
cout << "\nThe new value of number is " << number << endl;
system ("pause");
return 0;
}
#include <iostream>
using namespace std;
void swap(float *, float*);
void main ( )
{ float a, b;
cout << “Enter real number a: “;
cin >> a;
cout << “Enter real number <b>: “;
cin >> b;
system("pause");
return 0;
}
void InchToCM(double * ptr)
{
for (int j = 0;j<MAX; j++)
*ptr *= 2.54; // ptr points to the elements of a[]
}