0

I'm trying to learn how to use pointers, and I'm trying to make a program that asks the user for a random number of integers they'd like to write in, and then printing them back to the user. Normally I'd use an array for this, but that defeats the whole purpose of learning pointers.

#include <stdio.h>
#include <malloc.h>

int main() {
    int numberAmount = 0;
    int *numbers;

    printf("Type the amount of numbers you are going to write: ");
    scanf("%i", &numberAmount);

    numbers = (int*) malloc(sizeof(numberAmount));

    if (numberAmount == 0) {
        printf("No numbers were given");
    }
    else {
        for (int i = 0; i < numberAmount; i++) {
            scanf("%i", numbers);
        }

        while (*numbers != 0) {
            printf("%i ", *numbers);
            numbers++;
        }
    }

    return 0;
}

This is what I've come up with so far, but it does not work.

Any ideas?

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 2
    `numbers = malloc(numberAmount * sizeof *numbers);` followed by `scanf("%i", numbers + i);` Also note that `numbers++;` is bad practice: you won't be able to `free()` the allocation unless you use a copy of the pointer value. Adding too that `while (*numbers != 0)` won't work: there is no 'sentinel' value and you need another loop with `i`. – Weather Vane Nov 02 '21 at 20:28
  • `malloc` wants the number of _bytes_ you want to reserve. `int`s are [multi-byte fields](https://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes), probably 4 on your system, so you need to multiply the number of `int`s you want (`numberAmount`) by the size of a single `int` (which is what `sizeof *numbers` does because `*numbers` is an `int` type. – yano Nov 02 '21 at 20:34

1 Answers1

1

In this part of your code

for (int i = 0; i < numberAmount; i++) {
    scanf("%i", numbers);
}

you're saving the number that the user inputted in the same memory location. So the value saved in the numbers pointer keeps changing whenever the user inputs a new integer instead of adding a new integer.

You can fix this by replacing scanf("%i", numbers); with scanf("%i", (numbers + i));. This way for every new input the user provides, it will be saved in the memory location next to numbers.

ZShadow01
  • 81
  • 3