C Arrays and Pointers
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers;
printf("First element: %d\n", numbers[0]);
printf("First element using pointer: %d\n", *ptr);
ptr++;
printf("Second element using pointer: %d\n", *ptr);
ptr = ptr + 2;
printf("Fourth element using pointer: %d\n", *ptr);
return 0;
}
Explanation:
1. #include <stdio.h>
: Includes the standard input-output library.
int main() {
: Begins the main function.int numbers[] = {1, 2, 3, 4, 5};
: Declares an array namednumbers
containing five integers: 1, 2, 3, 4, and 5.int *ptr = numbers;
: Declares a pointerptr
of type integer and assigns it the address of the first element of the arraynumbers
.printf("First element: %d\n", numbers[0]);
: Prints the value of the first element of the arraynumbers
.printf("First element using pointer: %d\n", *ptr);
: Prints the value pointed to byptr
, which is the first element of the arraynumbers
.ptr++;
: Increments the pointerptr
to point to the next element in the array.printf("Second element using pointer: %d\n", *ptr);
: Prints the value pointed to by the incrementedptr
, which is the second element of the arraynumbers
.ptr = ptr + 2;
: Moves the pointerptr
two positions ahead from its current position in the array.printf("Fourth element using pointer: %d\n", *ptr);
: Prints the value pointed to by the updatedptr
, which is the fourth element of the arraynumbers
.return 0;
: Indicates successful termination of themain
function.