gintautas
gintautas

Reputation: 23

scanf from function to array

I am trying to scanf values to an array from another function using pointer to pointer. Here's the code:

int initialize(int **arr, int count);

int main()
{
    int count;
    int *numbers;
    scanf("Enter the amount of numbers to enter: %d", &count);
    initialize(&numbers, count);
    free(numbers);
    return 0;
}

int initialize(int **arr, int count)
{
    int i = 0;
    *arr = calloc(count, sizeof(int));
    while(i < count)
    {
        printf("Nr. %d: ", i + 1);
        scanf("%d", &arr[i]);
        i++;
    }

    return 0;
}

It allocates the memory correctly, however, there seems to be a problem inside scanf function in initialize so it crashes after reading in first 2 numbers. Could you help solve it?

Upvotes: 2

Views: 81

Answers (1)

alk
alk

Reputation: 70941

arr is a pointer to pointer to int, so 1st make it a pointer to int (before using it like an array) by doing *arr.

So this

    scanf("%d", &arr[i]);

should be

    scanf("%d", &(*arr)[i]);

or its shorter equivalent

    scanf("%d", *arr + i);

Unrelated, but in C it should be at least

int main(void)

Unrelated^2: Sizes and indexes in C best are defined using size_t (coming with stdlib.h).

So the relevant part of your code would look like this:

int main(void)
{
  size_t count;
  int *numbers;
  scanf("Enter the amount of numbers to enter: %zu", &count);
  ...

int initialize(int **arr, size_t count)
{
  size_t i = 0;
  *arr = calloc(count, sizeof(int));
  while (i < count)
  ...

Last not least the code misses error checking for the relevant functions:

  • scanf()
  • calloc()

Error checking (along with logging the errors) is debugging for free!

Upvotes: 3

Related Questions