Unit 4
Pointers in C++
Q1. Define pointer operator and address
operator with example.
Ans:
The Address of Operator
&
The & is a unary operator
that returns the memory address of its operand. For example, if var is an
integer variable, then &var is its address. This operator has the same
precedence and right-to-left associativity as the other unary operators.
You should read the &
operator as "the address of" which means &var will
be read as "the address of var".
The Pointer Operator *
The second operator is indirection
Operator *, and it is the complement of &. It is a unary operator that
returns the value of the variable located at the address specified by its
operand.
#include <iostream>
using namespace std;
int main () {
int var;
int *ptr;
int val;
var = 3000;
// take the address of var
ptr = &var;
// take the value available at ptr
val = *ptr;
cout << "Value
of var :" << var << endl;
cout << "Value
of ptr :" << ptr << endl;
cout << "Value
of val :" << val << endl;
return 0;
}
Q2. Write a C++ program to declare a class
train with members as train no and name. accept display data for one object of
train. Use pointer to object to call functions of class.
Ans:
#include <iostream>
#include <string>
using namespace std;
class Train {
private:
int trainNo;
string name;
public:
// Function
to accept train data
void
acceptData() {
cout
<< "Enter train number: ";
cin
>> trainNo;
cout
<< "Enter train name: ";
cin.ignore(); // To ignore
newline left in buffer
getline(cin, name);
}
// Function
to display train data
void
displayData() const {
cout
<< "Train Number: " << trainNo << endl;
cout
<< "Train Name: " << name << endl;
}
};
int main() {
Train
*trainPtr = new Train(); // Creating an
object using a pointer
// Using
pointer to call member functions
trainPtr->acceptData();
cout
<< endl;
cout
<< "Train Details:" << endl;
trainPtr->displayData();
delete
trainPtr; // Free allocated memory
return 0;
}
Q3.
Explain concept of pointer with example.
Ans: A pointer however,
is a variable that stores the memory address as its value.
A pointer variable points to a data type (like int or string) of the same type, and is created with
the * operator. The address of the
variable you're working with is assigned to the pointer:
Example :
string food = "Pizza"; // A food variable of
type string
string*
ptr = &food; // A pointer variable, with the name ptr, that
stores the address of food
// Output
the value of food (Pizza)
cout
<< food << "\n";
// Output
the memory address of food (0x6dfed4)
cout
<< &food << "\n";
// Output
the memory address of food with the pointer (0x6dfed4)
cout
<< ptr << "\n";
Q4. Develop a C++ program to perform
arithmetic operation using pointer.
Ans:
#include <iostream>
using namespace std;
void add(int* a, int* b, int* result) {
*result = *a
+ *b;
}
void subtract(int* a, int* b, int* result) {
*result = *a
- *b;
}
void multiply(int* a, int* b, int* result) {
*result = *a
* *b;
}
void divide(int* a, int* b, float* result) {
if (*b != 0)
{
*result
= static_cast<float>(*a) / *b;
} else {
cout
<< "Error: Division by zero is not allowed." << endl;
}
}
int main() {
int num1,
num2;
int result;
float
divResult;
cout
<< "Enter two integers: ";
cin >>
num1 >> num2;
add(&num1, &num2, &result);
cout
<< "Addition: " << result << endl;
subtract(&num1, &num2, &result);
cout
<< "Subtraction: " << result << endl;
multiply(&num1, &num2, &result);
cout
<< "Multiplication: " << result << endl;
divide(&num1, &num2, &divResult);
if (num2 !=
0) {
cout
<< "Division: " << divResult << endl;
}
return 0;
}
The program defines four
functions for arithmetic operations (add, subtract, multiply, divide), each
accepting pointers to integers.
Inside main(), the user enters
two integers, which are then passed to the respective functions using pointers.
The arithmetic operations are performed and
displayed accordingly. For division, if the second number is zero, an error
message is displayed.
Output –
Enter two integers: 8 4
Addition: 12
Subtraction: 4
Multiplication: 32
Division: 2
Q5. State the advantages of pointer.
Ans:
- Enable dynamic memory allocation.
- Allow efficient array traversal.
- Support pass-by-reference for function parameters.
- Enable function pointers for dynamic function calls.
- Facilitate manipulation of structures and classes.
- Provide pointer arithmetic for direct memory access.
- Optimize memory usage and provide efficient handling of large
data structures.
- Enable the implementation of complex data structures like
linked lists and trees.
- Essential for system-level programming and hardware
interfacing.
Pointers are a powerful feature in C++, enabling flexibility, efficiency, and low-level memory control that are crucial in many programming scenarios.
Ans : Another answer in detail
Pointers in C++ provide several powerful
advantages that allow for more dynamic and flexible programming. Below are the
main advantages of using pointers:
1. Dynamic
Memory Allocation:
- Pointers enable dynamic memory allocation, meaning memory can be
allocated at runtime using functions like new and delete. This allows for
more efficient memory management, especially when the size of the data is
unknown at compile time.
Example:
int* p = new int(10); //
Dynamically allocating memory for an integer
2.
Efficient Array Handling:
- Pointers can be used to traverse arrays and manipulate their
elements efficiently. Instead of using index-based access, pointer
arithmetic can access elements directly.
Example:
int arr[5] = {1, 2, 3, 4, 5};
int* p = arr; // Pointer pointing
to the first element of the array
for (int i = 0; i < 5; i++) {
cout << *(p + i)
<< " "; // Accessing
array elements using a pointer
}
3.
Pass-by-Reference:
- Pointers allow functions to modify variables passed as arguments.
This is called pass-by-reference, where a pointer to the actual
variable is passed, allowing the function to modify its value directly.
Example:
void increment(int* ptr) {
(*ptr)++; // Dereferencing the pointer to modify the
actual variable
}
int main() {
int num = 10;
increment(&num); // Passing the address of num
cout << num; // Output: 11
}
4. Pointer
to Functions:
- Pointers can be used to store the addresses of functions, allowing
dynamic selection of functions at runtime. This is particularly useful in
implementing callbacks and function dispatch mechanisms.
Example:
void displayMessage() {
cout << "Hello,
World!" << endl;
}
int main() {
void (*funcPtr)() =
displayMessage; // Pointer to function
funcPtr(); // Calling the function using the pointer
}
5. Pointer
to Structures and Classes:
- Pointers can be used to manipulate objects of structures or
classes. This allows for more efficient memory usage when working with
large data structures, such as linked lists or trees.
Example:
struct Node {
int data;
Node* next;
};
Node* head = new Node(); //
Dynamically allocating memory for a Node
6. Pointer
Arithmetic:
- Pointers support arithmetic operations like increment (++),
decrement (--), addition, and subtraction. This enables traversal of
memory addresses in arrays or other contiguous memory structures.
Example:
int arr[] = {10, 20, 30};
int* ptr = arr;
cout << *ptr << endl;
// Output: 10
ptr++;
cout << *ptr << endl;
// Output: 20
7.
Efficient Memory Usage:
- Pointers can save memory by pointing to existing data rather than
making copies. This is especially useful in cases where the data is large,
such as in linked lists, trees, and graphs.
8. Support
for Complex Data Structures:
- Pointers are essential in the implementation of complex data
structures such as linked lists, binary trees, graphs,
and hash tables. These data structures rely heavily on dynamic
memory allocation and efficient manipulation of pointers.
Example:
- Linked List:
struct Node {
int data;
Node* next;
};
Node* head = nullptr;
9.
Interfacing with Hardware and System-Level Programming:
- Pointers allow low-level manipulation of memory and hardware,
making them essential for system-level programming, such as writing device
drivers or working with embedded systems.
10.
Efficient Passing of Large Data Structures:
- Instead of passing large objects or arrays by value, which results
in copying, pointers allow efficient passing of references to such
structures, minimizing memory overhead and speeding up execution.
Example:
void processLargeArray(int* largeArray) {
// Efficient processing
without copying the array
}
11.
Supports Recursive Data Structures:
- Pointers are necessary for defining recursive data structures such
as trees and linked lists, where each element contains a reference
(pointer) to another element of the same type.
Q6. Explain reference and dereference
operators w.rt. pointer.
Ans:
. Reference
Operator (&):
- The reference operator (&) is used to obtain the memory
address of a variable.
- When applied to a variable, it returns the address where the
variable is stored in memory. This address can then be stored in a
pointer.
Example :
int num = 10;
int* ptr = #
// Reference operator: ptr now holds the address of num
Dereference
Operator (*):
- The dereference operator (*) is used to access the value
stored at the address that a pointer is pointing to.
- When applied to a pointer, it accesses the actual value at the
memory location that the pointer holds.
int num = 10;
int* ptr = #
// Pointer stores the address of num
cout << *ptr << endl; // Dereference operator: Output will be 10
Q7. Describe 'this'
pointer in C++ with an example
Ans.
this pointer is a special pointer that is automatically passed to
all non-static member functions of a class. It points to the object for which
the member function is called. The this pointer is used to refer to the current
object within a class, particularly when there is ambiguity between member
variables and parameters with the same name.
Key Points
About this Pointer:
1.
Implicitly Passed: The this pointer is implicitly passed to all non-static member
functions.
2.
Points to Current Object: It points to the object that invoked the member function.
3.
Cannot Be Modified: The value of the this pointer cannot be modified inside a function.
4.
Available in Non-static
Functions: The this pointer is only available in
non-static member functions because static functions belong to the class, not
to any specific object.
5.
Used to Return the Current
Object: The this pointer is often used in method
chaining or when returning the object itself from a member function.
Example
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
//
Constructor using 'this' pointer to resolve ambiguity
Rectangle(int length, int width) {
this->length = length; //
'this' resolves ambiguity between parameter and member
this->width = width;
}
// Method to
set dimensions using 'this'
Rectangle& setLength(int length) {
this->length = length; //
Using 'this' to refer to the current object's length
return
*this; // Returning the current object
by dereferencing 'this'
}
Rectangle& setWidth(int width) {
this->width = width;
return
*this;
}
// Method to
display the dimensions of the rectangle
void
display() {
cout
<< "Length: " << length << ", Width: "
<< width << endl;
}
};
int main() {
Rectangle
rect(10, 5);
rect.display(); // Output:
Length: 10, Width: 5
// Method
chaining using 'this' pointer
rect.setLength(15).setWidth(8);
rect.display(); // Output:
Length: 15, Width: 8
return 0;
}
No comments:
Post a Comment