Search code examples
cpointersscanfdynamic-memory-allocation

How to use scanf() correctly when reading input into an array using pointers?


For some reason, reading input using scanf() won't work this way:

int main() {
    int arr1_size = 0;

    // Reading array size
    scanf("%d", &arr1_size);

    int* arr1 = (int*) malloc(sizeof(int) * arr1_size);

    // Reading and printing array values
    for(int i = 0; i < arr1_size; i++) {
        scanf("%d", arr1);
        arr1++;
    }
    for(int i = 0; i < arr1_size; i++) {
        printf("%d", arr1[i]);
    }

    return 0;
}

What could be the issue?


Solution

  • Here is a slightly improved version of your program:

    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main() {
        int arr1_size = 0;
    
        printf("Hello,\nPlease enter the size of the first array:");
        scanf("%d", &arr1_size);
    
        int *arr1 = (int*) malloc(sizeof(int) * arr1_size);
    
        printf("\nPlease enter arr1 of size %d:\n", arr1_size);
        for(int i = 0; i < arr1_size; i++) {
            scanf("%d", arr1 + i);
        }
        printf("\nArray contents:\n");    
        for(int i = 0; i < arr1_size; i++) {
            printf("%d \n", arr1[i]);
        }
    
        return 0;
    }
    

    Execution:

    ./scan
    Hello,
    Please enter the size of the first array:3
    
    Please enter arr1 of size 3:
    1
    2
    3
    
    Array contents:
    1 
    2 
    3