The relationship between arrays and pointers in C is a fundamental concept that allows for efficient manipulation of data structures. This program illustrates how arrays and pointers work together and demonstrates their similarities and differences.
Program: Array and Pointer Relationship
Here's a simple C program that shows how to use arrays and pointers to manipulate data:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is included to use input/output functions likeprintf
andscanf
.
Variable Declarations:
int arr[5];
: This declares an array of 5 integers.int *ptr;
: This declares a pointer to an integer.
Input Values:
- The program prompts the user to enter 5 integers, which are stored in the
arr
array using afor
loop and thescanf
function.
- The program prompts the user to enter 5 integers, which are stored in the
Pointer Assignment:
- The pointer
ptr
is assigned the address of the first element of the array:ptr = arr;
. In C, the name of the array represents the address of its first element.
- The pointer
Display Array Elements Using Array Indexing:
- A
for
loop is used to print each element of the array using array indexing.
- A
Display Array Elements Using Pointer Arithmetic:
- Another
for
loop is used to access and print each element of the array using pointer arithmetic. Here,*(ptr + i)
accesses the element at indexi
in the array through the pointer.
- Another
Modify Array Elements Using Pointer:
- This section of the code demonstrates how to modify the elements of the array using the pointer. The statement
*(ptr + i) += 5;
increases each element by 5.
- This section of the code demonstrates how to modify the elements of the array using the pointer. The statement
Display Modified Array Elements:
- Finally, the modified values of the array are printed using the original array indexing method.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code:Execute the Program:
Example Output
When you run the program, the output might look like this:
Conclusion
This program demonstrates the relationship between arrays and pointers in C. It highlights how arrays can be manipulated using pointers, showing both indexing and pointer arithmetic. Understanding this relationship is crucial for working effectively with data structures in C, enabling more powerful and flexible code.