Programming Fundamentals (COMP1112) Pointers
Programming Fundamentals (COMP1112) Pointers
(COMP1112)
Lecture 7
Pointers
Pointer
• A pointer is a variable that is used to store a memory address. The
reference operator is used to store the memory address of a variable
and store it in a pointer.
• Pointer is declared as:
DataType *var;
• DataType : It is the type of variable pointed by the pointer variable
• * : It indicates that the var is a pointer variable
• var: It is name of the pointer variable
Pointer in C++
Example to use pointer
int n;
int *ptr;
cout<<“enter an integer”;
cin>>n;
ptr=&n;
cout<<“value of n:”<<n<<endl;
cout<<“address of n:”<<ptr<<endl;
cout<<name [i];
i++;
}
cout<<i;
Example 2: Array of characters
char name[20], *ptr;
cout<<“enter your name”;
cin.get(name, 20);
ptr=name;
cout<<“name entered is”<< ptr; //why not *ptr, it will print just first char
Note: the pointer displays the values stored in each element of the array
name until it finds null character \0
Sequential search vs Binary search
int arr[6]={10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int n, mid, end, start, loc; if(loc==-1)
cin>>n; cout<<“not found”<<endl;
loc=-1; else
end=9; cout<<n<<“ found at index “<<loc;
start=0;
while(start<=end)
{ mid=(start+end)/2;
if(arr[mid]==n)
{
loc=mid;
break;
}
else
if(n<arr[mid])
end=mid-1;
else
start=mid+1;
}
References
• C++ How to Program
By Deitel & Deitel
• Object oriented programming using C++ by Tasleem Mustafa, Imran Saeed, Tariq Mehmood, Ahsan Raza
• https://www.tutorialspoint.com/cplusplus
• http://ecomputernotes.com/cpp/introduction-to-oop
• http://www.cplusplus.com/doc/tutorial
• https://www.guru99.com/c-loop-statement.html
• www.w3schools.com