CLass Note3
CLass Note3
• *: Dereference operator, used to access the value stored at the address the pointer is pointing
to.
c
CopyEdit
printf("Address of a: %p\n", &a); // Prints memory address of 'a'
printf("Value pointed to by p: %d\n", *p); // Dereferencing
• It's a good practice to initialize pointers to NULL to avoid them pointing to garbage values.
Void Pointer
A void* can hold the address of any data type, but cannot be dereferenced directly without
casting.
c
CopyEdit
void *ptr;
int num = 10;
ptr = # // void pointer can store any address
Pointer to Pointer
A pointer that points to another pointer.
c
CopyEdit
int **ptr2ptr;
int *ptr;
int a = 10;
ptr = &a;
ptr2ptr = &ptr; // ptr2ptr points to ptr, which points to a
Function Pointer
A pointer that points to a function instead of a variable.
c
CopyEdit
void (*func_ptr)(int); // Declare a function pointer
void print_num(int x) {
printf("%d\n", x);
}
func_ptr = print_num;
func_ptr(10); // Calls print_num with argument 10
int main() {
MyClass *obj = new MyClass(); // Dynamically create an object
obj->x = 50;
obj->display();
delete obj; // Free dynamically allocated object
}
• Pointer arithmetic works because the pointer is adjusted based on the size of the data type.
For example, if arr is an integer array, ptr + 1 advances ptr by the size of an integer.
Pointer Comparison
Pointers can be compared to check if they point to the same memory location.
c
CopyEdit
if(ptr1 == ptr2) {
printf("Pointers are equal\n");
}
• Best practice: After freeing memory, set the pointer to NULL to avoid using dangling
pointers.
Memory Leaks
• Memory leaks occur when dynamically allocated memory is not freed.
• Best practice: Always free() memory when you are done using it.
Segmentation Faults
• Dereferencing uninitialized or NULL pointers causes segmentation faults.
• Best practice: Always initialize pointers and check for NULL before dereferencing.
Conclusion
• Pointers are one of the most powerful yet complex features in C and C++ programming.
• Understanding pointers is crucial for dynamic memory management, function references,
and efficient array handling.
• In C++, smart pointers help manage memory automatically, reducing errors like memory
leaks and dangling pointers.