What is Pointer to an array? Give one example.
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:
int numbers[5] = {1, 2, 3, 4, 5};
int *ptr = numbers;
int second_number = *ptr + 1;
Another example:
int *ptr = malloc(sizeof(int) * 5);
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:
#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!