Diana
Diana

Reputation: 363

How to dynamically allocate an array in a function?

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;
}

Upvotes: 1

Views: 85

Answers (2)

0___________
0___________

Reputation: 68099

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);

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 142080

*(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);
    }
}

Upvotes: 3

Related Questions