PF LAB 11
PF LAB 11
Course Instructor:
Lab Instructor:
Declaring pointers:
• Just like other variables, pointers have to be declared before their usage.
Syntax:
int x=5;
int *p;
p=&x;
• Data type of variable and pointer must be same like in this case int x and int *p.
• The & or address operator, is a unary operator that returns the address of its operand.
#include <iostream>
using namespace std;
int main(){
int* pc;
int c =
22;;
cout<<"Address of c:"<<&c<<endl;
cout<<"Value of c: "<<c<<endl;
pc=&c;
cout<<"Address of pointer pc: "<<pc<<endl;
cout<<"Content of pointer pc: "<<*pc<<endl;
c=11;
cout<<"Address of pointer pc: "<<pc<<endl;
cout<<"Content of pointer pc: "<<*pc<<endl;
*pc=2;
cout<<"Address of c: "<<&c<<endl;
cout<<"Value of c: "<<c<<endl;
return 0;
}
The output of the program is:
Example 2: Addition of two numbers making use of pointers
#include <iostream>
using namespace std;
int main(){
int first, second, *p, *q, sum;
cout<<"Enter two integers to add:";
cin>>first>>second;
p = &first; q =
&second; sum
= *p + *q;
cout<<"Sum of entered numbers: "<<sum<<endl;
return 0;
}
#include <iostream>
#include <ctime>
using namespace
std;
void getSeconds(unsigned long *par);
int main () {
unsigned long sec;
getSeconds( &sec );
#include <iostream>
using namespace std;
// function declaration
double getAverage(int *arr, int size);
int main () {
// an int array with 5 elements
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
return 0;
}
double getAverage(int *arr, int size) {
int i, sum = 0; double avg;
for (i = 0; i < size; ++i) { sum
+= arr[i];
}
avg = double(sum) / size;
return avg;
}