C Pointers and Arrays
In C programming language, pointers and arrays are closely related. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably.
If we assign this value to a non-constant pointer of the same type, then we can access the elements of the array using this pointer.
Example 1: Accessing Array Elements using Pointer with Array Subscript
// C Program to access array elements using pointer
#include <stdio.h>
void geeks()
{
// Declare an array
int val[3] = { 5, 10, 15 };
// Declare pointer variable
int* ptr;
// Assign address of val[0] to ptr.
// We can use ptr=&val[0];(both are same)
ptr = val;
printf("Elements of the array are: ");
printf("%d, %d, %d", ptr[0], ptr[1], ptr[2]);
return;
}
// Driver program
int main()
{
geeks();
return 0;
}
Not only that, as the array elements are stored continuously, we can pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements.
Example 2: Accessing Array Elements using Pointer Arithmetic
// C Program to access array elements using pointers
#include <stdio.h>
int main()
{
// defining array
int arr[5] = { 1, 2, 3, 4, 5 };
// defining the pointer to array
int* ptr_arr = arr;
// traversing array using pointer arithmetic
for (int i = 0; i < 5; i++) {
printf("%d ", *ptr_arr++);
}
return 0;
}
This concept is not limited to the one-dimensional array, we can refer to a multidimensional array element as well using pointers.
To know more about pointers to an array, refer to this article – Pointer to an Array
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.
In this article, we will discuss C pointers in detail, their types, uses, advantages, and disadvantages with examples.