What is Pointer to an array? Give one example.

28 Dec 2022 Balmiki Mandal 0 C Programming

Understanding Pointer to an Array with an Example

A pointer to an array is a pointer that stores the address of the first element of an array. It can be used to access any element of the array by adding the index of the element to the pointer.

For example, the following code declares an array of integers and a pointer to the array:

C-Programming
int numbers[5] = {1, 2, 3, 4, 5};
int *ptr = numbers;
The pointer ptr stores the address of the first element of the array, which is numbers[0]. We can access the second element of the array by using the pointer as follows:
 
C-Programming
int second_number = *ptr + 1;
 This code first dereferences the pointer ptr to get the value of the first element of the array. Then, it adds 1 to that value to get the value of the second element.

Another example:

C-Programming
int *ptr = malloc(sizeof(int) * 5);
This code allocates memory for an array of 5 integers and assigns the address of the allocated memory to the pointer ptr. Now, the pointer ptr points to the first element of the array.

Pointers to arrays can be used to perform a variety of operations on arrays, such as iterating through the array, sorting the array, and searching the array.

Write a C program for pointer to an array:

C-Programming
#include 

int main() {
  int arr[5] = {1, 2, 3, 4, 5};
  int *ptr = arr;

  // Print the elements of the array using the pointer
  for (int i = 0; i < 5; i++) {
    printf("%d\n", *ptr++);
  }

  return 0;
}

This program first declares an array of 5 integers called arr. Then, it declares a pointer to an integer called ptr and initializes it to the address of the first element of the array (arr).

The next loop iterates through the array and prints the value of each element using the pointer. The pointer is incremented after each iteration to point to the next element of the array.

The output of the program is:

1
2
3
4
5

Further Reading:


What is Pointer to an array? Give one example.

Print The array element using Pointer to an array

Assingment of pointer to an array in c

Implications of Passing an Array and a Pointer to an Array as Function Arguments in C

 

Write a C program that uses a pointer to an array to find the sum of all elements.

Enroll Now:

C-Programming From Scratch to Advanced 2023-2024] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [[email protected]].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.