Pointers
Pointers
Pointers
• Pointers are one of the most powerful features in C, allowing direct
memory access, manipulation of data, and efficient handling of arrays
and dynamic memory
• Definition: pointer is a variableintthat
*p; stores the memory address of
another variable.
Syntax for declaring a Pointer
int *p;
Here, p is a pointer to an integer.
The * indicates that the variable p is a pointer, not a regular integer.
Declaring and Initializing a
Pointer
• To declare a pointer, use the * symbol to indicate that the variable is a
pointer.
• To assign a value to the pointer, use the address-of operator (&).
int a = 10;
int *p;
p = &a; // p now stores the memory address of 'a‘
int main()
{
void (*func_ptr)() = greet; // Function pointer initialization
func_ptr(); // Call function using pointer
return 0;
}
Dynamic Memory Allocation
• Pointers are essential for dynamic memory management (e.g., malloc,
calloc, free).
• With pointers, you can allocate memory during runtime and manage
it manually.
int *p = (int*)malloc(sizeof(int)); // Allocating memory dynamically
*p = 10; // Storing a value in dynamically allocated memory
printf("%d", *p); // Prints 10
free(p); // Free allocated memory
Pointers and Structures
You can use pointers to work with structures, making it easier to
manipulate and pass structures to functions.
struct Person {
char name[50];
int age;
};
struct Person *p;
struct Person person = {"John", 25};
p = &person; // p points to person structure
printf("%s is %d years old.", p->name, p->age); // Access fields via pointer
Common Mistakes with Pointers