Welcome to our comprehensive guide on C Pointers! This tutorial is designed to help both beginners and intermediate learners understand the intricacies of pointers in C programming. By the end of this lesson, you'll be comfortable using pointers in your own projects. 📝 Note: This lesson is meant to be read sequentially for optimal learning.
<a name="intro"></a>
Pointers are variables that store the memory address of another variable. They allow us to manipulate the memory locations directly, making them an essential tool for managing memory efficiently.
<a name="ptr_var"></a>
A pointer variable holds the memory address of another variable. To declare a pointer, we use the * symbol before the variable name.
int num = 10;
int *ptr; // Declare a pointer to an integer
ptr = # // Assign the address of num to ptr<a name="ptr_not"></a>
There are two notations for pointers:
*ptr - Accesses the value stored at the memory address pointed by ptr&num - Returns the memory address of num<a name="mem_loc"></a>
Accessing memory locations directly using pointers allows for flexibility and efficiency. Here's how to access and modify the value stored at a memory address:
int num = 10;
int *ptr = #
*ptr = 20; // Change the value stored at the address pointed by ptr
printf("%d", num); // Output: 20<a name="arrays"></a>
Arrays can be treated as a sequence of memory locations, making pointers an ideal choice for array manipulation. To declare a pointer to an array, we use the [] symbol:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Declare a pointer to an array
printf("%d", *ptr); // Output: 1<a name="struct"></a>
Pointers can also be used with structures, allowing us to manipulate complex data types more efficiently.
typedef struct {
int id;
char name[20];
} Person;
Person person = {1, "John Doe"};
Person *ptr = &person;
printf("%d", ptr->id); // Output: 1<a name="mem_alloc"></a>
Dynamic memory allocation allows us to create variables at runtime, making our programs more flexible. The malloc() function is used to dynamically allocate memory:
int *ptr = (int *)malloc(5 * sizeof(int)); // Allocate memory for 5 integers
ptr[0] = 10;
ptr[1] = 20;
...<a name="funcs"></a>
Pointers can be used to pass and return data to functions, allowing for modular and reusable code.
void increment(int *ptr) {
(*ptr)++;
}
int num = 10;
int *ptr = #
increment(ptr);
printf("%d", num); // Output: 11<a name="examples"></a>
For a deeper understanding, check out these practical examples using pointers in C programming:
<a name="quiz"></a>
Test your understanding with these quiz questions:
What is the output of the following code?
What does the `[]` symbol represent in a pointer declaration?