0

I tried to make program to take some integers and write them in reversed order. When I input value for scanf_s program requires one more input and then moves on. Looks like that program does not write and read properly from and to memory. Code:

#include <stdio.h>
#include <stdlib.h>

void readValues(int * arr, int * size) {
    while (arr != size) {
        printf("Input number: \n");
        scanf_s("%d ", arr);
        arr++;
    }
}

void printReversed(int * arr, int * size) {
    while(size != arr) {
        printf("%d ", *size);
        size--;
    };
}

int main() {
    int n;
    printf("Input number of values to read: \n");
    scanf_s("%d\n", &n);

    int * arr = (int*)malloc(n * sizeof(int));
    int * size = arr + n;

    readValues(arr, size);
    printReversed(arr, size);

    free(arr);
}

This is output

Mackovic
  • 37
  • 8
  • 1
    Don't use `scanf_s`, use `scanf`. And also: `scanf_s("%d\n", ...` -> `scanf("%d", ...`. – Jabberwocky Mar 23 '20 at 12:05
  • 1
    In `printReversed`, your pointer `size` is initially one beyond tha valid range of the array. Decrement before you use it. (That is, make `size--` the first stamenent in the loop or combine it with the condition to `while (size-- > arr) ...` – M Oehm Mar 23 '20 at 12:07
  • Also the symbol `size` is misleading, `size` is not the size of the array but the pointer to one element beyond the end of the `arr` array. – Jabberwocky Mar 23 '20 at 12:08
  • Your instructions were very useful, I fixed it and now it works as expected. Thank you very much :) – Mackovic Mar 23 '20 at 12:16

1 Answers1

3

In scanf_s("%d ", arr);, the space character in the string causes scanf_s to read all the white-space characters in the input, which means it has to read until it sees a non-white-space character (or the end of the input), which is why you see the program apparently needing one more “input” than you thought. You can remove the space character from the format string.

In printReversed, the first item you print is *size, but size points one beyond the end of the items. You need to move size--; to be before the printf, not after.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • And of course, the same thing happens with the `scanf_s("%d\n", &n);` in `main()`. But one doesn't notice it because one *expects* to enter some more numbers after providing the first input. – John Bollinger Mar 23 '20 at 12:14
  • Yeah that was the problem, thank you so much :) – Mackovic Mar 23 '20 at 12:14