0

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?

4
  • 4
    You're losing the starting address of arr1 here: scanf("%d", arr1); arr1++;. I think more correctly, scanf is working as expected, printf is not. Commented Jun 1, 2020 at 17:44
  • Use scanf("%d", arr1 + i); to preserve the pointer from malloc. Then printf will work correctly. Commented Jun 1, 2020 at 17:46
  • Before issuing malloc it would be better to go on only if(arr1_size > 0) Commented Jun 1, 2020 at 17:50
  • Thank you, everyone! Commented Jun 1, 2020 at 18:06

1 Answer 1

1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Could you please explain what exactly went wrong? I understand that after my scan arr1 didn't point to the initial address anymore but doesn't printing with indices fix this? Did the scan I used work at all?
As already said, when entering data for an array with scanf you need to use the adress of the "ith" array element (arr1 + i) when entering the "ith" data item. In addition I have modified printf so that each array item is printed on its own line: it's easier to see what is printed (for a small array of course).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.