Print The array element using Pointer to an array in c
Print the Array Element Using Pointer to an Array
To print the element of an array using a pointer to an array, you can use the following steps:
- Declare a pointer to the array.
- Initialize the pointer to point to the first element of the array.
- Use a loop to iterate through the array, dereferencing the pointer at each step to print the element.
C Code prints the elements of an integer array using a pointer to an array:
C Programming
#include
int main() {
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *ptr = array; // Initialize the pointer to point to the first element of the array
// Iterate through the array and print the elements
for (int i = 0; i < 10; i++) {
printf("%d ", *ptr);
ptr++; // Increment the pointer to point to the next element of the array
}
printf("\n");
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
You can also use a pointer to an array to print the elements of a 2D array. To do this, you can use a nested loop to iterate through the array, dereferencing the pointer at each step to print the element.
C code prints the elements of a 2D integer array using a pointer to an array:
C Programming
#include
int main() {
int array[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int *ptr = array; // Initialize the pointer to point to the first element of the array
// Iterate through the array and print the elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", *ptr);
ptr++; // Increment the pointer to point to the next element of the array
}
printf("\n");
}
return 0;
}
Output:
1 2 3
4 5 6
7 8 9
Further Reading:
What is Pointer to an array? Give one example.
Print The array element using Pointer to an array
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.
Assingment of pointer to an array in c
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!