如何动态内存分配比数组更好吗? [英] how is dynamic memory allocation better than array?

查看:277
本文介绍了如何动态内存分配比数组更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想知道这是怎么动态内存分配,如果我可以只存储10 INT 项目的内存块?我可以只使用阵列和存储elemets动态使用的索引。为什么上面的方法更好呢?

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 ?

我是新的C,这是我第2天,我可能听起来很蠢,所以请多多包涵。

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

推荐答案

在这种情况下,你可以与在运行时分配一个变量替换10。这样,你可以决定你有多大的存储空间需要。但随着阵列,您必须指定一个整数声明中保持不变。所以,你不能决定是否为被宣布,甚至更糟,它可能是不够的,用户将真正需要尽可能多的位置。

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.

通过这样的动态分配,你可以指定一个更大的内存位置和第一位置的内容复制到新的给予,作为所需的阵列已经成长了IM pression。

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.

这篇关于如何动态内存分配比数组更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆