C pointers
Created By: chatGPT
Pointers in C are variables that store the memory address of another variable. They provide a way to interact with memory directly, allowing for efficient data manipulation. When you use pointers, you can perform operations like modifying the value of a variable indirectly or dynamically allocating memory. The syntax for declaring a pointer involves using the
*
operator.int *ptr;
// Declare an integer pointer
int num = 10;
ptr = # // Store the address of num in ptr
You can access the value at the address pointed to by a pointer using the dereference operator (
*
). This allows you to read or modify the value stored in that memory location.// Accessing value through pointer
printf("Value of num: %d\n", *ptr); // Output: 10
*ptr = 20; // Change value of num to 20
printf("New value of num: %d\n", num); // Output: 20
Pointer arithmetic allows you to perform operations on pointers, such as adding or subtracting integers. This is particularly useful when dealing with arrays, as pointers can be incremented to traverse through the elements.
int arr[] = {1, 2, 3, 4, 5};
int *p = arr; // Pointer to the first element
for(int i = 0; i < 5; i++) {
printf("%d ", *(p + i)); // Output: 1 2 3 4 5
}
Dynamic memory allocation in C is done using pointers. Functions such as
malloc
, calloc
, and free
in the <stdlib.h>
library allow you to allocate and free memory as needed during program execution. Always ensure to free dynamically allocated memory to prevent memory leaks.#include <stdlib.h>
int *array;
array = (int *) malloc(5 * sizeof(int)); // Allocating memory for 5 integers
if (array == NULL) {
// Handle allocation failure
}
// Use the array
for (int i = 0; i < 5; i++) {
array[i] = i + 1;
}
free(array); // Free allocated memory
It's essential to initialize pointers before use to avoid undefined behavior. Uninitialized pointers can point to random memory locations, leading to unpredictable results.
int *ptr = NULL; // Initialize pointer to NULL
if (ptr != NULL) {
printf("Pointer is pointing to: %d", *ptr);
} else {
printf("Pointer is NULL, no value to display.");
}