Review 01
Review 01
int x=3; 6
int &y=x;
cout<<x+y;
Example
defining variable x. and assigning to it different names
m,n,z
int x=4;
int &z=x;
16
int&m=x,&n=x;
cout<<x+m+n+z;
Static Pointers
A pointer is a variable that contains the address of
another variable of the same data type
int x=4;
cout<<"adrs of x="<<&x<<endl; adrs of x=0x7ffe805ec44c
int *p=&x; adrs of x is p=0x7ffe805ec44c
cout<<"adrs of x is p="<<p;
double x=5; 15
double &z=x;
double *p=&x;
if(x==*p && z==*p)
cout<<x+*p+z;
int x=1;
int *p=&x;
p++;
*p=2; 321
p++;
*p=3;
cout<<*p;
p--;
cout<<*p;
p--;
cout<<*p;
______________________________________________________________________________
_
}
Page
NULL pointer
We must assign a pointer to NULL to prohibit programs
crashing
Dangling pointer not assigned to NULL (shorted pointers)
should be shorted or removed
Example
4
int *q=NULL;//initialize the pointer to null
int x=4;
q=&x;
cout<<*q; //output 4
q=NULL;
Example
int x(3); 39
cout<<x;
int *y=new int (9);
cout<<*y;
Example
3
Page
int m=int(7);
MEng. Samah A. Massadeh
int *q=&m; 85
++(*q) ; 55
56
cout<<*q;
int *y= new int(5);
cout<<*y<<endl;
*y=55;
cout<<*y<<endl;
++(*y);
cout<<*y;
Keyword: delete frees reserved memory locations
Dynamic pointers cause depletion of memory so we have
to remove them from the heap, by using delete keyword
to free the memory
When we use delete, the memory location will be freed
for writing new values but the old value remains until
we write over it
Example 9
1.14241e-313
double *z=new double(9.0);
cout<<*z<<endl;
delete z;
cout<<*z;
Example
4
5
Page
6
Page