![](/img/trans.png)
[英]How to print the values that are stored in the array using pointer and function in c
[英]how to print array elements using pointer in c?
請任何人檢查我的代碼中是否有任何問題我在循環中使用 *(ptr+i) 來打印數組的元素,但它沒有提供所需的輸出! 有人請幫幫我! 使用指針獲取數組的輸入和輸出
#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;
}
修改ptr后,錯過了數組的第一個元素地址。 在進入打印機循環之前,您需要重新分配第一個元素地址。 查看固定代碼:
#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.