I had an exercise telling me to input elements into an array by only using pointers. So I looked for a solution in the WEB ( https://codeforwin.org/2017/11/c-program-input-print-array-elements-using-pointers.html)
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int N, i;
int * ptr = arr; // Pointer to arr[0]
printf("Enter size of array: ");
scanf("%d", &N);
printf("Enter elements in array:\n");
for (i = 0; i < N; i++)
{
scanf("%d", ptr);
// Move pointer to next array element
ptr++;
}
// Make sure that pointer again points back to first array element
ptr = arr;
printf("Array elements: ");
for (i = 0; i < N; i++)
{
// Print value pointed by the pointer
printf("%d, ", *ptr);
// Move pointer to next array element
ptr++;
}
return 0;
}
I can't understand this specific line:
for (i = 0; i < N; i++)
{
scanf("%d", ptr);
// Move pointer to next array element
ptr++;
}
Why do we use ptr without dereferencing it with (*ptr). ptr is an address since ptr = arr. When we use scanf we type in a value (int or double or float) and not an address, so why's that pointer without a *?
Thank you.
scanfare pointers. This is from earlier in your code:scanf("%d", &N);