Home > Back-end >  Store a given amount of numbers using pointers in C
Store a given amount of numbers using pointers in C

Time:11-03

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?

CodePudding user response:

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.

  • Related