简体   繁体   English

如何在c中使用指针打印数组元素?

[英]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 !!请任何人检查我的代码中是否有任何问题我在循环中使用 *(ptr+i) 来打印数组的元素,但它没有提供所需的输出! 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.修改ptr后,错过了数组的第一个元素地址。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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