Operations on Pointers and Concept of dynamic memory allocation
#Operations on Pointers Concept of dynamic memory allocation c language
Introduction
Understanding pointer operations and dynamic memory allocation is crucial for efficient memory management in C programming. Pointers allow direct access to memory addresses, improving performance and flexibility.
&
)
The &
operator is used to retrieve the memory address of a variable.
#include <stdio.h>
int main() {
int a = 10; // Variable declaration
int *p; // Pointer variable declaration
p = &a; // Store address of variable a in pointer p
printf("Address stored in pointer p: %p\n", p); // Accessing the address
printf("Value stored at pointer p: %d\n", *p); // Accessing the value
return 0;
}
A null pointer is a pointer that does not point to any memory address. It is initialized with NULL
to avoid unexpected behavior.
#include <stdio.h>
int main() {
int *p = NULL; // Null pointer
printf("Value inside pointer p: %p\n", p);
return 0;
}
A wild pointer is an uninitialized pointer that may cause undefined behavior.
#include <stdio.h>
int main() {
int *p; // Wild pointer
printf("%d", *p); // May cause runtime error
return 0;
}
Dynamic memory allocation allows managing memory during runtime using functions like malloc
, calloc
, and realloc
.
#include <stdio.h>
#include <stdlib.h>
int main() {
// Allocate memory for an integer array
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}
// Initialize the array
for (int i = 0; i < 5; ++i) {
arr[i] = i * 2;
}
// Print array elements
for (int i = 0; i < 5; ++i) {
printf("%d ", arr[i]);
}
// Free allocated memory
free(arr);
return 0;
}
malloc(size_t size)
: Allocates a specified number of bytes and returns a pointer to the allocated memory.calloc(size_t num, size_t size)
: Allocates memory for an array of elements and initializes them to zero.realloc(void *ptr, size_t new_size)
: Resizes previously allocated memory.free(void *ptr)
: Deallocates previously allocated memory to prevent memory leaks.Pointer operations and dynamic memory allocation play a vital role in C programming by optimizing memory usage and program efficiency. Understanding these concepts is essential for writing high-performance applications while avoiding memory-related errors.