Pointers in C
Pointers are variables that store memory addresses. They provide a powerful way to manipulate memory and improve performance.
Declaring and Initializing Pointers
1. Declaration
A pointer is declared using the *
operator.
int *ptr; // Declaring a pointer to an integer
2. Initialization
Pointers store the address of another variable.
int num = 10;
int *ptr = # // Pointer stores the address of num
Accessing Values using Pointers
The *
operator (dereference) is used to access the value at the memory location.
printf("Value of num: %d", *ptr); // Outputs 10
Pointer Arithmetic
Pointers support arithmetic operations such as increment, decrement, addition, and subtraction.
ptr++; // Moves to the next memory location
Pointers and Arrays
An array name acts as a pointer to the first element of the array.
int arr[] = {1, 2, 3};
int *ptr = arr; // Points to the first element
printf("%d", *(ptr + 1)); // Outputs 2
Pointers and Functions
Pointers can be used to pass variables by reference to functions.
void changeValue(int *p) {
*p = 20; // Modifies the original value
}
int main() {
int num = 10;
changeValue(&num);
printf("%d", num); // Outputs 20
}
Pointer to Pointer
A pointer can store the address of another pointer.
int num = 10;
int *ptr = #
int **pptr = &ptr; // Pointer to pointer
printf("%d", **pptr); // Outputs 10
Dynamic Memory Allocation
Pointers are used for dynamic memory allocation with functions like malloc()
, calloc()
, and free()
.
Example: Allocating Memory Dynamically
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) malloc(sizeof(int));
*ptr = 50;
printf("Value: %d", *ptr);
free(ptr); // Free allocated memory
}
Pointers are essential in C programming for memory management, data structures, and efficient programming techniques.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.