Introduction to Pointers in C
What is a Pointer?
A pointer in C is a variable that stores the memory address of another variable. Instead of holding a data value, a pointer holds the address of a variable where data is stored. This allows for efficient array manipulation, memory management, and dynamic memory allocation.
Declaration of Pointers
Pointers are declared using the * operator. The syntax for declaring a pointer is:
data_type *pointer_name;
For example, to declare a pointer to an integer:
int *ptr;
Initializing Pointers
Pointers are initialized by assigning the address of another variable to the pointer. The address-of operator & is used to obtain the address of a variable.
int var = 10;
int *ptr = &var; /* ptr now holds the address of var */
Dereferencing Pointers
Dereferencing a pointer involves accessing the value stored at the memory address held by the pointer. The * operator is used for dereferencing.
int var = 10;
int *ptr = &var;
int value = *ptr; /* value now holds the value of var */
Pointer Arithmetic
Pointers can be incremented or decremented to point to the next or previous memory location. The amount by which a pointer is incremented or decremented depends on the data type it points to.
int arr[3] = {10, 20, 30};
int *ptr = arr;
ptr++; /* Now ptr points to arr[1] */
Example Program
Let's look at a complete example of using pointers in a C program:
#include <stdio.h>
int main() {
int var = 10;
int *ptr = &var;
printf("Address of var: %p\n", (void*)&var);
printf("Address stored in ptr: %p\n", (void*)ptr);
printf("Value of var: %d\n", var);
printf("Value pointed to by ptr: %d\n", *ptr);
return 0;
}
The output of the above program would be:
Address of var: 0x7ffee3b12a9c Address stored in ptr: 0x7ffee3b12a9c Value of var: 10 Value pointed to by ptr: 10
Conclusion
Pointers are a fundamental concept in the C language that provide a powerful way to manage memory and interact with data. By understanding how to declare, initialize, and use pointers, you can write more efficient and flexible C programs.