0

So I started learning C a few days ago. I heard that dynamic memory allocation is a important thing in C. I also know how malloc(), realloc() and free() work but I don't really know why/when I should use it. For example when I don't know how many values I want to store in an array, I could use malloc(). Kind of like this:

    //With malloc()
    int n2;
    printf("How many values do you want to store now?");
    scanf("%d", &n2);
    int* ptr = malloc(sizeof(int) * n2);
    for(int i = 0; i < n2; i++)
    {
        int val;
        scanf("%d", &val);
        *(ptr+i) = val;
    }
    printf("Second Array:\n");
    for(int i = 0; i < n2; i++)
    {
        printf("Array[%d]: %d\n", i, *(ptr+i));
    }

    free(ptr);

But why should I use malloc() here? I could create the array also like this:

    //Without malloc()
    int n1;
    printf("How many values do you want to store?\n");
    scanf("%d", &n1);
    int arr1[n1];
    for(int i = 0; i < n1; i++)
    {
        int val;
        scanf("%d", &val);
        arr1[i] = val;
    }
    printf("First Array:\n");
    for(int i = 0; i < n1; i++)
    {
        printf("Array[%d]: %d\n", i, arr1[i]);
    }

So why/when should I use malloc()?

Butzti
  • 3
  • 1

0 Answers0