1

I am trying to dynamically allocate an array passed through a parameter in the function dynamic_allocation_array and I don't understand why isn't it working.

#include <stdio.h>
#include <stdlib.h>
void dynamic_allocation_array(int **a, int n){

    (*a) = (int *)malloc(n * sizeof(int *));
    for(int i = 0; i < n; i++){
        scanf("%d", *(a + i));
    }

}
int main()
{
    int n, *a;
    scanf("%d", &n);
    dynamic_allocation_array(&a, n);
    for(int i = 0; i < n; i++){
        printf("%d ", a[i]);
    }
    return 0;
}
2
  • you over complicate the simple thing. Functions have return values to handle it. Double pointers are needed if you return something and need to return the pointer as well. Commented May 5, 2019 at 15:56
  • using your login malloc prototype should look like this void malloc(void **, size_t); Commented May 5, 2019 at 16:04

2 Answers 2

3

*(a + i) is invalid. You want first to * dereference the a pointer , then add + i. The a points to some variable, there is no at a + i. You allocated memory at (*a) + i.

Also you want to allocate the memory for n count of ints, not for n pointers to int. You want: malloc(n * sizeof(int)).

Use temp variable, don't use *(a + b) just use a[b] notation, make it clearer:

void dynamic_allocation_array(int **a, int n) {
    int *tmp = malloc(n * sizeof(int));
    for(int i = 0; i < n; i++){
        scanf("%d", &tmp[i]);
    }

    *a = tmp;
}

or you can:

void dynamic_allocation_array(int **a, int n) {
    *a = malloc(n * sizeof(int));
    for(int i = 0; i < n; i++){
        scanf("%d", &(*a)[i]);
    }
}

or you can:

void dynamic_allocation_array(int **a, int n) {
    *a = malloc(n * sizeof(int));
    for(int i = 0; i < n; i++){
        scanf("%d", *a + i);
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Shouldn't it be malloc(n * sizeof(int)) ? Since memory is needed for n values, not n pointers.
... or instead of (int*) even better, as safer: sizeof *tmp or sizeof **a.
Best would be n * sizeof **a.
best will ne removing the double pointer and return the allocated space reference instead
the idea with the temporary variable is a life-saving tip. Now I don't need to worry about this many pointers when the teacher requires us to use a function :)
2

I would not use any double pointers as it is 100% not needed here

int *dynamic_allocation_array(size_t size)
{
      int *a = malloc(size * sizeof(*a));
       /* another code */
      return a;
}

and in the calling function

int *a = dynamic_allocation_array(some_size);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.