Pointers
Definition: A variable that holds the
address of another
object or variable
Syntax
Example: #include
<iostream>
#include
<string>
using
namespace std;
int main()
{
int a=5, b=10;
int *c = &a; //int *c; c = &a;
cout<<"a is "<<a<<endl;
cout<<"&a is "<<&a<<endl; //print address of a
cout<<"c is "<<c<<endl; // c stores address of a
cout<<"&c is "<<&c<<endl; //print address of c
cout<<"*c is "<<*c<<endl<<endl; //dereference operator *. c points to a. print what is in a.
*c=b;
cout<<"a is "<<a<<endl;
cout<<"b is "<<b<<endl;
cout<<"*c is "<<*c<<endl;
system("pause");
return 0;
}
Example:
int n; // n is an integer variable
int *pi; // pi is a pointer
to an int variable
pi = &n; // pi is holding the address of n
// (pi is pointing to n)
// int *pi; pi = &n; is equivalent
to int *pi = &n;
*pi = 100; // puts 100 at the location pointed to by pi
char c; // c is a char variable
char
*pc; // pc is a pointer to a
char variable
pc = &c; // pc is holding the address of c
// (pc is pointing to c)
*pc = 'A'; // puts 'A' at the location pointed to by pc
ADT of a Pointer (pp 50-51)
data
operations (Let ptr
be a pointer variable, u and v
be pointer expressions,
and var be a variable of type T.)
Pointer Arithmetic
ptr + i points
to the i-th data object to the right of ptr. The actual address produced
depends
on the size of the data object type being pointed to.
Specific Examples:
| Data Type | Current Address of ptr | New address generated |
| char (1 byte) | ptr = 5000 | ptr + 1 == 5001 |
| int (2 bytes) | ptr = 5000 | ptr + 3 == 5000 + 3 * 2 == 5006 |
| double (4 bytes) | pts = 5000 | ptr - 6 == 5000 - 6 * 4 == 4976 |
Code Example:
char str[] = "ABCDEFG";
// char array
char *PC = str;
short X = 33;
short *PX = &X;
cout << *PC <<
endl; // output: A
PC += 4;
// PC = PC + 4; (Now PC points to E.)
cout << *PC <<
endl; // output: E
PC--;
// PC = PC - 1; (Now PC points to D.)
cout << *PC <<
endl; // output: D
cout << *PX +
3 << endl; // (33 + 3) output: 36
Types of Memory Allocation