C Pointers

Pointers are an important concept in the C programming language. They allow you to store the memory address of a variable and manipulate its contents. Pointers are represented by the * symbol, and are used in conjunction with the & symbol, which represents the address of a variable.

To declare and assign a pointer in C, you first declare a variable to store the memory address, and then use the & operator to retrieve the address of a variable and assign it to the pointer. The * symbol is used to denote that the variable is a pointer.

Example 1: Basic Pointer Usage

The following example demonstrates how to use a pointer to store the address of a variable and then manipulate its contents:

1#include <stdio.h> 2 3int main() { 4 int x = 10; 5 int *ptr; 6 7 ptr = &x; 8 9 printf("The value of x is: %d\n", x); 10 printf("The address of x is: %p\n", &x); 11 printf("The value stored in the pointer is: %p\n", ptr); 12 printf("The value pointed to by the pointer is: %d\n", *ptr); 13 14 *ptr = 20; 15 16 printf("\nAfter changing the value pointed to by the pointer:\n"); 17 printf("The value of x is: %d\n", x); 18 19 return 0; 20}

Output:

1The value of x is: 10 2The address of x is: 0x7ffcee7d959c 3The value stored in the pointer is: 0x7ffcee7d959c 4The value pointed to by the pointer is: 10 5 6After changing the value pointed to by the pointer: 7The value of x is: 20

In this example, we declare an integer variable x with a value of 10. We then declare a pointer ptr and assign the address of x to it using the & operator. The printf function is used to display the value of x, its address, the value stored in the pointer, and the value pointed to by the pointer. Finally, we change the value pointed to by the pointer using the *ptr = 20 assignment, and the value of x is displayed again to show that the change was made.

Example 2: Pointer Arithmetic

Pointers can be incremented and decremented just like normal variables, and the size of the data type pointed to can be used to calculate the distance between two memory locations. The following example demonstrates pointer arithmetic in C:

1#include <stdio.h> 2 3int main() { 4 int x[5] = {10, 20, 30, 40, 50}; 5 int *ptr; 6 7 ptr = x; 8 9 for (int i = 0; i < 5; i++) { 10 printf("The value stored at x[%d] is: %d\n", i, *ptr); 11 ptr++; 12 } 13 14 return 0; 15}

Output:

1The value stored at x[0] is: 10 2The value stored at x[1] is: 20 3The value stored at x[2] is: 30 4The value stored at x[3] is: 40 5The value stored at x[4] is: 50

In this example, an integer array x with five elements is declared, and a pointer ptr is assigned the address of the first element of the array. The for loop is used to traverse