0% found this document useful (0 votes)
23 views10 pages

Lab # 10 Pointers in C++

Uploaded by

alizarizwan006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views10 pages

Lab # 10 Pointers in C++

Uploaded by

alizarizwan006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

University of Management and Technology

Department of Artificial Intelligence


CC1021L Programming Fundamentals Lab
Fall 2023
Participant ID: Participant Name:

Date: Total Marks: Obtained Marks:

Lab # 10: Pointers in C++


Learning Objectives
 Develop
Pointers in C++
In C++, a pointer is a variable that holds the memory address of another variable. It is a
fundamental concept in C++ programming and allows for dynamic memory allocation, efficient
manipulation of data structures, and direct access to memory. Pointers are a powerful and
essential concept in C++ programming. They allow for direct manipulation of memory addresses
and provide mechanisms for dynamic memory allocation and efficient data manipulation.
In C++, a pointer is a special type of variable that stores the memory address of another variable.
Instead of holding the actual value of the data, a pointer holds the location (address) where the
data is stored in memory. This allows for indirect access to the data through the pointer.

Example 1
#include <iostream>
using namespace std;

int main() {
// Declare a variable
int x = 42;

// Declare a pointer and initialize it with the address of the


variable
int *ptr = &x;

// Display the value and address of the variable


cout << "Value of x: " << x << endl;
cout << "Address of x: " << &x << endl;

// Display the value and address stored in the pointer


cout << "Value pointed to by ptr: " << *ptr << endl;
cout << "Address stored in ptr: " << ptr << endl;

return 0;
}
Pointer Declaration
data_type* pointer_variable_name;
int* ptr;
Above statement defines ptr as pointer variable of type integer.
Pointers in C++ store memory addresses by holding the value that represents the location or
address of another variable in the computer's memory. Here's how it works:
1. Declaration: When you declare a pointer variable, you are essentially reserving a space
in memory to store an address. The type of the pointer indicates the type of data it is
intended to point to.
int *ptr; // declares a pointer to an integer
2. Initialization: To store the memory address of a variable in a pointer, you use the
address-of operator (&). This operator returns the memory address of the specified
variable.
int x = 10;
int *ptr = &x; // initializes the pointer with the address of
variable x
3. Dereferencing: The pointer can be used to access the value stored at the memory address
it points to. This is known as dereferencing and is done using the dereference operator
(*).
int value = *ptr; // retrieves the value stored at the memory address
pointed to by ptr
In this example, *ptr dereferences the pointer ptr, allowing you to access the value stored in
the memory location it points to.
4. Pointer Arithmetic: Pointers can be manipulated using pointer arithmetic, which
involves adding or subtracting an integer value to the pointer. This operation adjusts the
pointer to point to a different memory location.
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // points to the first element of the array

// pointer arithmetic to access the second element


int secondElement = *(ptr + 1);

In the example above, ptr + 1 calculates the memory address of the second element in the
array, and *(ptr + 1) dereferences that address to retrieve the value.

Reference and Dereference Operator


In C++ programming, the reference and dereference operators are crucial for working with
pointers and references.
1. Reference Operator (&)
The reference operator (&) is used to obtain the memory address of a variable. It is also known
as the "address-of" operator. When applied to a variable, it returns the memory address where the
variable is stored.

int x = 42;
int *ptr = &x; // & is the reference operator, gets the address of x
In this example, &x retrieves the memory address of the variable x, and the pointer ptr is
assigned this address.
2. Dereference Operator (*)
The dereference operator (*) is used to access the value stored at the memory address pointed to
by a pointer. It is also used with references to access the value referred to by a reference.
int y = *ptr; // * is the dereference operator, gets the value at the
address pointed to by ptr
In this example, *ptr retrieves the value stored at the memory address pointed to by the pointer
ptr, and it is assigned to the variable y.

The dereference operator is also used when working with pointers and arrays to access elements.
int arr[3] = {10, 20, 30};
int *arrPtr = arr;
int firstElement = *arrPtr; // Accesses the first element of the
array

Example 2
#include <iostream>
using namespace std;

int main() {

int* pc, c;

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;
}
Output of Program:
Address of c: [memory_address_1]
Value of c: 22
Address of pointer pc: [memory_address_1]
Content of pointer pc: 22
Address of pointer pc: [memory_address_1]
Content of pointer pc: 11
Address of c: [memory_address_1]
Value of c: 2

Common Mistakes when working with pointers\


Suppose, you want pointer pc to point to the address of c. Then,
int c, *pc;

1. // Wrong! 'pc' is a pointer, whereas 'c' is not an address.


pc = c;

2. // Wrong! '*pc' is the value pointed by an address, whereas '&c' is an address.


*pc = &c;

3. // Correct! 'pc' is a pointer, and '&c' is also an address.


pc = &c;

4. // Correct! '*pc' is the value pointed by an address, and 'c' is also a value (not an address).
*pc = c;

Example 3
In this example, C++ code initializes an integer variable, updates its value using a pointer, and
then prints the original and updated values.
#include <iostream>
using namespace std;

int main() {
int myNumber = 42; // Initialize an integer variable

// Declare a pointer to an integer and initialize it with the


address of myNumber
int *ptr = &myNumber;

// Print the original value of myNumber


cout << "Original Value: " << myNumber << endl;

// Use the pointer to update the value of myNumber


*ptr = 99;

// Print the updated value of myNumber


cout << "Updated Value: " << myNumber << endl;

return 0;
}
Output of the above program is:
Original Value: 42
Updated Value: 99

Functions and Pointers


In C++, you can use pointers as function arguments to achieve various functionalities, such as
modifying values outside the function, passing arrays efficiently, and working with dynamic
memory.
Function has three mechanisms through which arguments can be passed:
1. Pass by Value
In pass by value, the actual value of the argument is passed to the function. Changes made to the
parameter inside the function do not affect the original argument outside the function. Simple
data types (integers, floats, characters) are typically passed by value.
void myFunction(int x) {
// Changes to 'x' do not affect the original argument
}
2. Pass by Reference
In pass by reference, the function receives a reference to the original variable. Changes made to
the parameter inside the function directly affect the original argument outside the function. The
reference is indicated by the & symbol.
void myFunction(int &x) {
// Changes to 'x' directly affect the original argument
}
3. Pass by Pointer
In pass by pointer, the function receives a pointer to the original variable. Changes made to the
value pointed to by the pointer inside the function affect the original argument outside the
function. The pointer is indicated by the * symbol.
void myFunction(int *x) {
// Changes to the value pointed to by 'x' affect the original
argument
}

Example
This example explains the concept of pass by value, reference and pointer as argument to a
function.
#include <iostream>
using namespace std;
void passByValue(int x) {
x++;
}

void passByReference(int &x) {


x++;
}

void passByPointer(int *x) {


(*x)++;
}

int main() {
int num = 10;

passByValue(num); // Pass by value


cout << "After passByValue: " << num << endl;

passByReference(num); // Pass by reference


cout << "After passByReference: " << num << endl;

passByPointer(&num); // Pass by pointer


cout << "After passByPointer: " << num << endl;

return 0;
}

The output of the above program will be:


After passByValue: 10
After passByReference: 11
After passByPointer: 12

The effects of passing arguments by value, by reference, and by pointer on memory are related to
how data is stored, accessed, and manipulated within functions.
1. Pass by Value:
Memory Usage:
 A copy of the argument is created in memory.
 The function works with the copied data, leaving the original data unchanged.
Memory Overhead:
 Increased memory overhead, especially for large data structures.
 Copying data consumes additional memory.
2. Pass by Reference:
Memory Usage:
 No new memory is allocated for the parameter.
 The function directly works with the memory location of the original variable.
Memory Overhead:
 Minimal memory overhead as no additional copies are made.
 Direct access to the original data.
3. Pass by Pointer:
Memory Usage:
 A memory address (pointer) is passed to the function.
 The function uses the memory location pointed to by the pointer.
Memory Overhead:
 Slightly higher overhead compared to pass by reference due to the need to manage a
pointer.
 More flexibility, especially for dynamic memory allocation.
Passing Array using Pointers as Argument in Function
In C++, there are several ways to pass an array to a function, and the choice depends on the
specific requirements and preferences of the programmer. Here are the common ways to pass an
array to a function:
Pass by Pointer:
1. Declare the function parameter as a pointer.
2. Pass the address of the array to the function.
3. Allows the function to modify the original array.
void myFunction(int* arr, int size);
Pass by Reference:
1. Declare the function parameter as a reference.
2. Pass the array directly to the function.
3. Allows the function to modify the original array.
void myFunction(int (&arr)[5]);
Pass by Value:
To pass an array by value to a function, you declare the function parameter as an array type.

void myFunction(int arr[5]) {


// Function code here
}
void myFunction(int arr[], int size) {
// Function code here
}
Passing an array by value in C++ is not a common practice and is generally not recommended,
especially for large arrays. When you pass an array by value, a copy of the entire array is made,
and this can result in inefficient memory usage and reduced performance. To pass an array to a
function using a pointer in C++, you can declare the function parameter as a pointer and then
pass the address of the array when calling the function.
Example: Here's an example of passing an array using reference and pointer.
#include <iostream>
using namespace std;

// Function to modify array elements using reference


void modifyArrayByReference(int (&arr)[5]) {
for (int i = 0; i < 5; ++i) {
arr[i] += 10;
}
}

// Function to modify array elements using pointer


void modifyArrayByPointer(int* arr, int size) {
for (int i = 0; i < size; ++i) {
arr[i] *= 2;
}
}

int main() {
int myArray[] = {1, 2, 3, 4, 5};

// Pass array by reference


modifyArrayByReference(myArray);

// Display modified array


cout << "Modified Array (by reference): ";
for (int i = 0; i < 5; ++i) {
cout << myArray[i] << " ";
}
cout << endl;

// Pass array by pointer


modifyArrayByPointer(myArray, 5);

// Display modified array


cout << "Modified Array (by pointer): ";
for (int i = 0; i < 5; ++i) {
cout << myArray[i] << " ";
}
cout << endl;

return 0;
}
Function Return Type as Pointer
A function with a return type of pointer is a function that returns the memory address (pointer) of
a variable or an object. This allows the function to provide access to a particular memory
location, which can be useful for various purposes such as dynamically allocated memory,
accessing global variables, or returning the address of local variables.
Declaration Syntax:
ReturnType* functionName(parameters);
 ReturnType*: This indicates that the function returns a pointer. ReturnType can be
any valid data type.
 functionName: The name of the function.
 parameters: Optional parameters that the function may take.
Here's an example of a C++ program demonstrating the concept of returning an integer pointer
from a function:
#include <iostream>
using namespace std;

// Function that returns a pointer to a local array


int* createArray(int size) {
int newArray[size]; // Local array

// Initialize the array elements


for (int i = 0; i < size; ++i) {
newArray[i] = i * 2;
}

// Return a pointer to the first element of the local array


return newArray;
}

// Function to display array elements


void displayArray(int* arr, int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
const int arraySize = 5;

// Call the function and get the pointer to the local array
int* myArray = createArray(arraySize);

// Display the array elements


cout << "Array elements: ";
displayArray(myArray, arraySize);
return 0;
}

Passing a structure as parameter in Function


Passing a struct as a parameter to a function in C++ allows you to operate on the structure's data
within the function. This helps in organizing related data and functions into a cohesive unit.
#include <iostream>
#include <string>

using namespace std;

// Define a struct named 'Person'


struct Person {
string name;
int age;
double height;
};

// Function that takes a pointer to a Person struct as a parameter


void displayPerson(const Person* p) {
if (p) {
cout << "Name: " << p->name << ", Age: " << p->age << ",
Height: " << p->height << endl;
} else {
cout << "Invalid pointer!" << endl;
}
}

int main() {
// Create a Person struct instance
Person john;
john.name = "John Doe";
john.age = 25;
john.height = 175.5;

// Call the function with a pointer to the struct as a parameter


displayPerson(&john);

return 0;
}

You might also like