2

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?

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works. Where could I find more detailed information on this scanf pointer thing?
@gintas: This is not an issue with scanf() (is always takes the address of the variable to scan into), but your confusion about the levels of indirection you implemented ... ;)

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.