C - Pointers
Pointers in C are variables that store memory addresses. They are used to manipulate and work with memory directly. Pointers enable you to dynamically allocate memory, access array elements, pass parameters by reference, and create complex data structures. Here's an introduction to pointers in C:
Declaring a Pointer:
To declare a pointer variable, you use the asterisk (*) symbol before the variable name. For example:
int *ptr; // Declaration of an integer pointer
char *str; // Declaration of a character pointer
Assigning a Memory Address to a Pointer:
You can assign a memory address to a pointer using the address-of operator (&) or by assigning the result of another pointer assignment. For example:
int number = 10;
int *ptr = &number; // Assigning the address of 'number' to 'ptr'
Accessing the Value Pointed by a Pointer:
To access the value stored at the memory address pointed to by a pointer, you use the dereference operator (*) before the pointer variable. For example:
int number = 10;
int *ptr = &number;
printf("Value of 'number': %d\n", *ptr); // Accessing the value using the dereference operator
Changing the Value Pointed by a Pointer:
You can change the value stored at the memory address pointed to by a pointer by assigning a new value to the dereferenced pointer. For example:
int number = 10;
int *ptr = &number;
*ptr = 20; // Changing the value using the dereference operator
printf("New value of 'number': %d\n", number);
Pointer Arithmetic:
Pointers in C can be incremented or decremented to navigate through memory. Pointer arithmetic operates based on the size of the data type the pointer is pointing to. For example:
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers;
printf("Value at index 2: %d\n", *(ptr + 2)); // Accessing the value at index 2 using pointer arithmetic
Pointers and Arrays:
In C, arrays and pointers are closely related. An array name can be treated as a pointer to its first element. For example:
int numbers[] = {1, 2, 3, 4, 5};
printf("Value at index 0: %d\n", *numbers); // Accessing the value using the array name as a pointer
Pointers and Function Parameters:
Pointers are often used in function parameters to pass variables by reference. By passing a pointer to a function, changes made to the variable inside the function will affect the original variable. For example:
void changeValue(int *ptr) {
*ptr = 100; // Changing the value using the dereference operator
}
int main() {
int number = 10;
changeValue(&number); // Passing the address of 'number'
printf("New value of 'number': %d\n", number);
return 0;
}
These are some basic concepts related to pointers in C. Pointers are a powerful feature in C programming that allows direct manipulation of memory addresses and provides flexibility in memory management.