C Array Input with Pointers

In C language, we can input elements in an array using pointers. Here is an example code:

#include <stdio.h>

int main() {
    int n;
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int arr[n];
    int *ptr = arr;  // 使用指针指向数组的第一个元素

    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", ptr + i);  // 使用指针来输入数组元素
    }

    printf("The entered elements are: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", *(ptr + i));  // 使用指针来访问数组元素
    }

    return 0;
}

In this example, the user is first asked to input the number of elements in the array. Then, an array ‘arr’ of size n is created and a pointer ‘ptr’ is used to point to the first element of the array. Next, a loop is used with the pointer to input the elements of the array. Finally, another loop is used with the pointer to access and output the array elements.

bannerAds