Search code examples
cpointersinputdereference

Input array using only pointers


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.


Solution

  • Why do we use ptr without dereferencing it with (*ptr).

    We're passing scanf the pointer to memory on which to write the int that it gets from the keyboard. To dereference is to follow that pointer ourselves, which doesn't help scanf know where to write the value.

    When we use scanf we type in a value (int or double or float) and not an address so why's that ptr without * ?

    The & in &N is the address-of operator, meaning "make me a pointer to N". You could write int *N_ptr = &N; then scanf("%d", N_ptr); if that makes it clearer.

    One other thing: passing arguments/parameters in C is done by copy. Meaning:

    void some_function(int i) {
      printf("%p\n", &i);
    }
    int main(void) {
      int i;
      printf("%p\n", &i);
      some_function(i);
    }
    

    This is guaranteed to print out two different pointer values. There have to be two ints in memory because if some_function modifies i, that does not modify i in the caller. This is why scanf can't just use address-of itself to get the original address: it would only get the address of the copy it received and that copy is gone before the caller can read it.