how is dynamic memory allocation better than array

2019-08-02 14:57发布

int numbers*;
numbers = malloc ( sizeof(int) * 10 );

I want to know how is this dynamic memory allocation, if I can store just 10 int items to the memory block ? I could just use the array and store elemets dynamically using index. Why is the above approach better ?

I am new to C, and this is my 2nd day and I may sound stupid, so please bear with me.

7条回答
太酷不给撩
2楼-- · 2019-08-02 15:08

Array is used to allocate memory statically and in one go. To allocate memory dynamically malloc is required.

e.g. int numbers[10];

This will allocate memory statically and it will be contiguous memory.

If you are not aware of the count of the numbers then use variable like count.

int count;
int *numbers;
scanf("%d", count);
numbers = malloc ( sizeof(int) * count );

This is not possible in case of arrays.

查看更多
做个烂人
3楼-- · 2019-08-02 15:19

Array size is defined at compilation time whereas dynamic allocation is done at run time.

Thus, in your case, you can use your pointer as an array : numbers[5] is valid.

If you don't know the size of your array when writing the program, using runtime allocation is not a choice. Otherwise, you're free to use an array, it might be simpler (less risk to forget to free memory for example)

Example:

  • to store a 3-D position, you might want to use an array as it's alwaays 3 coordinates
  • to create a sieve to calculate prime numbers, you might want to use a parameter to give the max value and thus use dynamic allocation to create the memory area
查看更多
太酷不给撩
4楼-- · 2019-08-02 15:20

In this case you could replace 10 with a variable that is assigned at run time. That way you can decide how much memory space you need. But with arrays, you have to specify an integer constant during declaration. So you cannot decide whether the user would actually need as many locations as was declared, or even worse , it might not be enough.

With a dynamic allocation like this, you could assign a larger memory location and copy the contents of the first location to the new one to give the impression that the array has grown as needed.

This helps to ensure optimum memory utilization.

查看更多
萌系小妹纸
5楼-- · 2019-08-02 15:20

In the example you gave

int *numbers;
numbers = malloc ( sizeof(int) * 10 );

there are no explicit benefits. Though, imagine 10 is a value that changes at runtime (e.g. user input), and that you need to return this array from a function. E.g.

int *aFunction(size_t howMany, ...)
{
    int *r = malloc(sizeof(int)*howMany);
    // do something, fill the array...
    return r;
}

The malloc takes room from the heap, while something like

int *aFunction(size_t howMany, ...)
{
    int r[howMany];
    // do something, fill the array...
    // you can't return r unless you make it static, but this is in general
    // not good
    return somethingElse;
}

would consume the stack that is not so big as the whole heap available.

More complex example exists. E.g. if you have to build a binary tree that grows according to some computation done at runtime, you basically have no other choices but to use dynamic memory allocation.

查看更多
爷、活的狠高调
6楼-- · 2019-08-02 15:23

There is a difference with where the memory is allocated. Using the array syntax, the memory is allocated on the stack (assuming you are in a function), while malloc'ed arrays/bytes are allocated on the heap.

/* Allocates 4*1000 bytes on the stack (which might be a bit much depending on your system) */
int a[1000];

/* Allocates 4*1000 bytes on the heap */
int *b = malloc(1000 * sizeof(int))

Stack allocations are fast - and often preferred when:

  • "Small" amount of memory is required
  • Pointer to the array is not to be returned from the function

Heap allocations are slower, but has the advantages:

  • Available heap memory is (normally) >> than available stack memory
  • You can freely pass the pointer to the allocated bytes around, e.g. returning it from a function -- just remember to free it at some point.

A third option is to use statically initialized arrays if you have some common task, that always requires an array of some max size. Given you can spare the memory statically consumed by the array, you avoid the hit for heap memory allocation, gain the flexibility to pass the pointer around, and avoid having to keep track of ownership of the pointer to ensure the memory is freed.

Edit: If you are using C99 (default with the gnu c compiler i think?), you can do variable-length stack arrays like

int a = 4;
int b[a*a];
查看更多
家丑人穷心不美
7楼-- · 2019-08-02 15:24

Dynamic does not refer to the access. Dynamic is the size of malloc. If you just use a constant number, e.g. like 10 in your example, it is nothing better than an array. The advantage is when you dont know in advance how big it must be, e.g. because the user can enter at runtime the size. Then you can allocate with a variable, e.g. like malloc(sizeof(int) * userEnteredNumber). This is not possible with array, as you have to know there at compile time the (maximum) size.

查看更多
登录 后发表回答