简体   繁体   中英

how to print array elements using pointer in c?

please anyone check is there any issue in my code i am using *(ptr+i) in loop to print elements of array but it is not giving desired output !! someone please help me out!! taking input and output of array using pointer

#include <stdio.h>

int main()
{
    int arr[5];
    int *ptr = &arr[0];
    for (int i = 0; i < 5; i++) {
        printf("enter the value of array at place %d : ", i + 1);
        scanf("%d", ptr);
        ptr++;
    }
    for (int i = 0; i < 5; i++) {
        printf("value of array at place %d is %d\n", i + 1, *(ptr + i));
        // ptr++;
    }

    return 0;
}

After you modify the ptr, you miss the first element address of the array. You need to reassign the first element address before entering the printer loop. See the fixed code:

#include <stdio.h>

int main()
{
    int arr[5];
    int *ptr = arr; // You can assign an array of the first element directly using the identifier.
    for (int i = 0; i < 5; i++) {
        printf("enter the value of array at place %d : ", i + 1);
        scanf("%d", ptr);
        ptr++;
    }
    ptr = arr; // This line was missing
    for (int i = 0; i < 5; i++) {
        printf("value of array at place %d is %d\n", i + 1, *(ptr + i));
        // ptr++;
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM