0% found this document useful (0 votes)
26 views

Pointers 1

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

Pointers 1

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

POINTERS

Subtopics
• Introduction to Pointers
• Syntax
• Types of Pointer
• Uses of pointers
• Applications of Pointers
• Pointer Arithmetic
• Dynamic Memory Allocation
• Common Pointer Errors
• Conclusion
Definition of Pointer
A pointer is a variable that stores the
memory address of another variable. Instead of
holding actual data, a pointer holds the location
where the data is stored in memory. This allows
programs to directly access and manipulate data in
memory.
Key Points:

1.Memory Address Storage:


•Pointers are used to store the addresses of variables or
objects in memory.
•Example: If a variable x is stored at address 0x100, a
pointer p can store this address.

2.Indirect Access:
•Through pointers, you can indirectly access or modify the
value of the variable they point to using the dereference
operator (*).

3.Dynamic Behavior:
•Pointers enable dynamic memory allocation, passing
variables by reference, and creating complex data
structures like linked lists, trees, etc.
Pointer Syntax
Declaration:
syntax: data_type *pointer_name;
Example: int *ptr;
Initialization:
syntax: pointer_name = &variable;
Example:
int x = 10;
int *ptr = &x; // ptr now holds the address of x
Dereferencing:
Access the value stored at the memory address using *.
Example:
printf("%d", *ptr); // Outputs the value of x
Uses Of Pointers
Key Uses:

• Dynamic Memory
Management: Allocating and
freeing memory.
• Function Arguments: Pass-by-
reference for efficiency.
• Data Structures: Building linked
lists, trees, and graphs.
• System Programming: Direct
memory manipulation.
• Efficiency: Reduced overhead in
accessing data.
Types Of Pointers
Null Pointer:

• A pointer explicitly initialized to NULL (or nullptr in C++), indicating


it points to no valid memory location.

Example Code:

int *ptr = NULL; // Pointer is initialized to NULL


if (ptr == NULL) {
printf("Pointer is null.\n");
}

Void Pointer:
• A generic pointer of type void * that can store the address of any
data type but cannot be dereferenced directly.
Example:
int a = 10;
void *ptr = &a; // Generic pointer
printf("Value: %d\n", *(int *)ptr); // Typecast required
Function Pointer:
A pointer that holds the address of a function, enabling
functions to be passed as arguments or called indirectly.
Syntax:
return_type (*function_pointer)(parameter_list);
Example Code:
int add(int a, int b) {
return a + b;
}
int (*func_ptr)(int, int) = add; // Pointer to add()
printf("Sum: %d\n", func_ptr(5, 10)); // Indirect function call
Double Pointer:
A pointer that stores the address of another pointer,
effectively creating a chain of pointers.

Syntax:
data_type **pointer_name;

Example Code:
int x = 10;
int *p = &x;
int **pp = &p;
printf("Value of x: %d\n", **pp); // Accessing x via double pointer
Applications of Pointers
Dynamic Memory Allocation:

Pointers are used to allocate memory during program execution using


functions like malloc(), calloc(), realloc(), and free() in C, or new and
delete in C++.

Example:

int *ptr = (int *)malloc(5 * sizeof(int)); // Allocate memory for


5 integers
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1; // Initialize the memory
}
free(ptr); // Free the allocated memory

• Allocate memory when the size is unknown during compile-time.


• Avoid wastage of unused memory in fixed-size arrays.
Pointer Arithmetic
Pointer arithmetic refers to the manipulation of pointers to access or
modify elements in memory. Pointers allow direct access to memory locations
and arithmetic operations make it easier to navigate through arrays or data
structures.

Increment (++)
•Moves the pointer to the next memory location.
•For example, if a pointer points to an integer (int), it moves by sizeof(int) bytes.

int arr[] = {10, 20, 30};


int *ptr = arr; // Points to the first element
ptr++; // Now points to the second element
printf("%d", *ptr); // Output: 20

Decrement(--)
Moves the pointer to the previous memory location.

int arr[] = {10, 20, 30};


int *ptr = &arr[2]; // Points to the third element
ptr--; // Now points to the second element
printf("%d", *ptr); // Output: 20
Addition (+)

Advances the pointer by a specified number of elements.

int arr[] = {10, 20, 30};


int *ptr = arr; // Points to the first element
ptr = ptr + 2; // Now points to the third element
printf("%d", *ptr); // Output: 30

Subtraction (-)

•Moves the pointer backward by a specified number of elements or calculates the


distance between two pointers.

int arr[] = {10, 20, 30};


int *ptr = &arr[2]; // Points to the third element
ptr = ptr - 2; // Now points to the first element
printf("%d", *ptr); // Output: 10
Dynamic Memory Allocation
Dynamic memory allocation is the process of allocating memory
during program runtime. This allows programs to manage memory more
efficiently, especially when the amount of required memory is not known
beforehand. It is an essential feature of programming languages like C,
C++, and others.

Types:

• Malloc()
• Calloc()
• Realloc()
• Free()
 malloc (Memory Allocation)
• The memory is uninitialized (contains garbage values).
• Returns a pointer to the first byte of the allocated memory or NULL if allocation
fails.
• Allocates a specified number of bytes of memory.

Syntax:

void* malloc(size_t size);

Example:
int* ptr = (int*) malloc(5 * sizeof(int));

 calloc (Contiguous Allocation)


• Allocates memory for an array of elements, initializes all elements to zero.
• Returns a pointer to the allocated memory.

Syntax:

void* calloc(size_t n, size_t size);


 realloc (Reallocate Memory)
• Adjusts the size of previously allocated memory without losing its content.
• May move the memory block to a new location.

Syntax:
void* realloc(void* ptr, size_t size);

Example:
ptr = (int*) realloc(ptr, 10 * sizeof(int));
 free (Deallocate Memory)
• Frees memory allocated by malloc, calloc, or realloc.
• Prevents memory leaks.
Syntax:
void free(void* ptr);
Example:
free(ptr);
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(sizeof(int));
// Check if memory allocation was successful
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Assign and print a value
*ptr = 42;
printf("Value stored in dynamically allocated memory: %d\n", *ptr);
// Free the memory
free(ptr);
return 0;

} Output:
Common Pointer
Pointers are a Errors
powerful feature in C and C++, but improper
handling can lead to significant issues in the program. Here are
some of the most common pointer errors, along with their causes,
explanations, and ways to avoid them.
Dereferencing a Null Pointer
A null pointer is a pointer that doesn't point to any valid memory
address. Dereferencing a null pointer occurs when you try to access
memory using a null pointer, which leads to undefined behavior and
usually results in a segmentation fault or crash.
Cause
A pointer is initialized to NULL or nullptr and is later dereferenced
without being assigned a valid memory address.
int *ptr = NULL;
printf("%d", *ptr);
Conclusion

Pointers are a crucial feature in languages like C and C++,


offering direct memory access for efficient data manipulation, dynamic
memory allocation, and complex data structures. They enable pass-by-
reference, saving memory and improving performance, especially with
large data sets. Mastering pointers is essential for writing efficient and
optimized programs, though they can be challenging to learn. Proper
use of pointers greatly enhances memory management and program
performance.
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy